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

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

from ccxt.async_support.base.exchange import Exchange
import asyncio
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 AccountSuspended
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
from ccxt.base.errors import BadSymbol
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidAddress
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import CancelPending
from ccxt.base.errors import NotSupported
from ccxt.base.errors import DDoSProtection
from ccxt.base.errors import RateLimitExceeded
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.errors import OnMaintenance
from ccxt.base.errors import InvalidNonce
from ccxt.base.errors import RequestTimeout
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise


class bitget(Exchange):

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

    def set_sandbox_mode(self, enabled):
        self.options['sandboxMode'] = enabled

    async def fetch_time(self, params={}):
        """
        fetches the current integer timestamp in milliseconds from the exchange server
        :param dict params: extra parameters specific to the bitget api endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        """
        response = await self.publicSpotGetPublicTime(params)
        #
        #     {
        #       code: '00000',
        #       msg: 'success',
        #       requestTime: 1645837773501,
        #       data: '1645837773501'
        #     }
        #
        return self.safe_integer(response, 'data')

    async def fetch_markets(self, params={}):
        """
        retrieves data on all markets for bitget
        :param dict params: extra parameters specific to the exchange api endpoint
        :returns [dict]: an array of objects representing market data
        """
        sandboxMode = self.safe_value(self.options, 'sandboxMode', False)
        types = self.safe_value(self.options, 'fetchMarkets', ['spot', 'swap'])
        if sandboxMode:
            types = ['swap']
        promises = []
        for i in range(0, len(types)):
            type = types[i]
            if type == 'swap':
                subTypes = None
                if sandboxMode:
                    # the following are simulated trading markets ['sumcbl', 'sdmcbl', 'scmcbl']
                    subTypes = ['sumcbl', 'sdmcbl', 'scmcbl']
                else:
                    subTypes = ['umcbl', 'dmcbl', 'cmcbl']
                for j in range(0, len(subTypes)):
                    promises.append(self.fetch_markets_by_type(type, self.extend(params, {
                        'productType': subTypes[j],
                    })))
            else:
                promises.append(self.fetch_markets_by_type(types[i], params))
        promises = await asyncio.gather(*promises)
        result = promises[0]
        for i in range(1, len(promises)):
            result = self.array_concat(result, promises[i])
        return result

    def parse_markets(self, markets):
        result = []
        for i in range(0, len(markets)):
            result.append(self.parse_market(markets[i]))
        return result

    def parse_market(self, market):
        #
        # spot
        #
        #    {
        #        symbol: 'ALPHAUSDT_SPBL',
        #        symbolName: 'ALPHAUSDT',
        #        baseCoin: 'ALPHA',
        #        quoteCoin: 'USDT',
        #        minTradeAmount: '2',
        #        maxTradeAmount: '0',
        #        minTradeUSDT": '5',
        #        takerFeeRate: '0.001',
        #        makerFeeRate: '0.001',
        #        priceScale: '4',
        #        quantityScale: '4',
        #        status: 'online'
        #    }
        #
        # swap
        #
        #    {
        #        symbol: 'BTCUSDT_UMCBL',
        #        makerFeeRate: '0.0002',
        #        takerFeeRate: '0.0006',
        #        feeRateUpRatio: '0.005',
        #        openCostUpRatio: '0.01',
        #        quoteCoin: 'USDT',
        #        baseCoin: 'BTC',
        #        buyLimitPriceRatio: '0.01',
        #        sellLimitPriceRatio: '0.01',
        #        supportMarginCoins: ['USDT'],
        #        minTradeNum: '0.001',
        #        priceEndStep: '5',
        #        volumePlace: '3',
        #        pricePlace: '1',
        #        symbolStatus: "normal",
        #        offTime: "-1",
        #        limitOpenTime: "-1"
        #    }
        #
        marketId = self.safe_string(market, 'symbol')
        quoteId = self.safe_string(market, 'quoteCoin')
        baseId = self.safe_string(market, 'baseCoin')
        quote = self.safe_currency_code(quoteId)
        base = self.safe_currency_code(baseId)
        supportMarginCoins = self.safe_value(market, 'supportMarginCoins', [])
        settleId = self.safe_string(supportMarginCoins, 0)
        settle = self.safe_currency_code(settleId)
        symbol = base + '/' + quote
        parts = marketId.split('_')
        typeId = self.safe_string(parts, 1)
        type = None
        swap = False
        spot = False
        future = False
        contract = False
        pricePrecision = None
        amountPrecision = None
        linear = None
        inverse = None
        expiry = None
        expiryDatetime = None
        if typeId == 'SPBL':
            type = 'spot'
            spot = True
            pricePrecision = self.parse_number(self.parse_precision(self.safe_string(market, 'priceScale')))
            amountPrecision = self.parse_number(self.parse_precision(self.safe_string(market, 'quantityScale')))
        else:
            expiryString = self.safe_string(parts, 2)
            if expiryString is not None:
                year = '20' + expiryString[0:2]
                month = expiryString[2:4]
                day = expiryString[4:6]
                expiryDatetime = year + '-' + month + '-' + day + 'T00:00:00Z'
                expiry = self.parse8601(expiryDatetime)
                type = 'future'
                future = True
                symbol = symbol + ':' + settle + '-' + expiryString
            else:
                type = 'swap'
                swap = True
                symbol = symbol + ':' + settle
            contract = True
            linear = (typeId == 'UMCBL') or (typeId == 'CMCBL') or (typeId == 'SUMCBL') or (typeId == 'SCMCBL')
            inverse = not linear
            priceDecimals = self.safe_integer(market, 'pricePlace')
            amountDecimals = self.safe_integer(market, 'volumePlace')
            priceStep = self.safe_string(market, 'priceEndStep')
            amountStep = self.safe_string(market, 'minTradeNum')
            precisePrice = Precise(priceStep)
            precisePrice.decimals = max(precisePrice.decimals, priceDecimals)
            precisePrice.reduce()
            priceString = str(precisePrice)
            pricePrecision = self.parse_number(priceString)
            preciseAmount = Precise(amountStep)
            preciseAmount.decimals = max(preciseAmount.decimals, amountDecimals)
            preciseAmount.reduce()
            amountString = str(preciseAmount)
            amountPrecision = self.parse_number(amountString)
        status = self.safe_string_2(market, 'status', 'symbolStatus')
        active = None
        if status is not None:
            active = (status == 'online' or status == 'normal')
        minCost = None
        if quote == 'USDT':
            minCost = self.safe_number(market, 'minTradeUSDT')
        return {
            'id': marketId,
            'symbol': symbol,
            'base': base,
            'quote': quote,
            'settle': settle,
            'baseId': baseId,
            'quoteId': quoteId,
            'settleId': settleId,
            'type': type,
            'spot': spot,
            'margin': False,
            'swap': swap,
            'future': future,
            'option': False,
            'active': active,
            'contract': contract,
            'linear': linear,
            'inverse': inverse,
            'taker': self.safe_number(market, 'takerFeeRate'),
            'maker': self.safe_number(market, 'makerFeeRate'),
            'contractSize': 1,
            'expiry': expiry,
            'expiryDatetime': expiryDatetime,
            'strike': None,
            'optionType': None,
            'precision': {
                'amount': amountPrecision,
                'price': pricePrecision,
            },
            'limits': {
                'leverage': {
                    'min': None,
                    'max': None,
                },
                'amount': {
                    'min': self.safe_number_2(market, 'minTradeNum', 'minTradeAmount'),
                    'max': self.safe_number(market, 'maxTradeAmount'),
                },
                'price': {
                    'min': None,
                    'max': None,
                },
                'cost': {
                    'min': minCost,
                    'max': None,
                },
            },
            'info': market,
        }

    async def fetch_markets_by_type(self, type, params={}):
        method = self.get_supported_mapping(type, {
            'spot': 'publicSpotGetPublicProducts',
            'swap': 'publicMixGetMarketContracts',
        })
        response = await getattr(self, method)(params)
        #
        # spot
        #
        #    {
        #        code: '00000',
        #        msg: 'success',
        #        requestTime: 1645840064031,
        #        data: [
        #            {
        #                symbol: 'ALPHAUSDT_SPBL',
        #                symbolName: 'ALPHAUSDT',
        #                baseCoin: 'ALPHA',
        #                quoteCoin: 'USDT',
        #                minTradeAmount: '2',
        #                maxTradeAmount: '0',
        #                takerFeeRate: '0.001',
        #                makerFeeRate: '0.001',
        #                priceScale: '4',
        #                quantityScale: '4',
        #                status: 'online'
        #            }
        #        ]
        #    }
        #
        # swap
        #
        #    {
        #        code: '00000',
        #        msg: 'success',
        #        requestTime: 1645840821493,
        #        data: [
        #            {
        #                symbol: 'BTCUSDT_UMCBL',
        #                makerFeeRate: '0.0002',
        #                takerFeeRate: '0.0006',
        #                feeRateUpRatio: '0.005',
        #                openCostUpRatio: '0.01',
        #                quoteCoin: 'USDT',
        #                baseCoin: 'BTC',
        #                buyLimitPriceRatio: '0.01',
        #                sellLimitPriceRatio: '0.01',
        #                supportMarginCoins: [Array],
        #                minTradeNum: '0.001',
        #                priceEndStep: '5',
        #                volumePlace: '3',
        #                pricePlace: '1'
        #            }
        #        ]
        #    }
        #
        data = self.safe_value(response, 'data', [])
        return self.parse_markets(data)

    async def fetch_currencies(self, params={}):
        """
        fetches all available currencies on an exchange
        :param dict params: extra parameters specific to the bitget api endpoint
        :returns dict: an associative dictionary of currencies
        """
        response = await self.publicSpotGetPublicCurrencies(params)
        #
        #     {
        #       code: '00000',
        #       msg: 'success',
        #       requestTime: 1645935668288,
        #       data: [
        #         {
        #           coinId: '230',
        #           coinName: 'KIN',
        #           transfer: 'false',
        #           chains: [
        #             {
        #               chain: 'SOL',
        #               needTag: 'false',
        #               withdrawable: 'true',
        #               rechargeable: 'true',
        #               withdrawFee: '187500',
        #               depositConfirm: '100',
        #               withdrawConfirm: '100',
        #               minDepositAmount: '12500',
        #               minWithdrawAmount: '250000',
        #               browserUrl: 'https://explorer.solana.com/tx/'
        #             }
        #           ]
        #         }
        #       ]
        #     }
        #
        result = {}
        data = self.safe_value(response, 'data', [])
        for i in range(0, len(data)):
            entry = data[i]
            id = self.safe_string(entry, 'coinId')
            code = self.safe_currency_code(self.safe_string(entry, 'coinName'))
            chains = self.safe_value(entry, 'chains', [])
            networks = {}
            for j in range(0, len(chains)):
                chain = chains[j]
                networkId = self.safe_string(chain, 'chain')
                network = self.safe_currency_code(networkId)
                withdrawEnabled = self.safe_string(chain, 'withdrawable')
                depositEnabled = self.safe_string(chain, 'rechargeable')
                networks[network] = {
                    'info': chain,
                    'id': networkId,
                    'network': network,
                    'limits': {
                        'withdraw': {
                            'min': self.safe_number(chain, 'minWithdrawAmount'),
                            'max': None,
                        },
                        'deposit': {
                            'min': self.safe_number(chain, 'minDepositAmount'),
                            'max': None,
                        },
                    },
                    'active': None,
                    'withdraw': withdrawEnabled == 'true',
                    'deposit': depositEnabled == 'true',
                    'fee': self.safe_number(chain, 'withdrawFee'),
                    'precision': None,
                }
            result[code] = {
                'info': entry,
                'id': id,
                'code': code,
                'networks': networks,
                'type': None,
                'name': None,
                'active': None,
                'deposit': None,
                'withdraw': None,
                'fee': None,
                'precision': None,
                'limits': {
                    'amount': {'min': None, 'max': None},
                    'withdraw': {'min': None, 'max': None},
                },
            }
        return result

    async def fetch_deposits(self, code=None, since=None, limit=None, params={}):
        """
        fetch all deposits made to an account
        see https://bitgetlimited.github.io/apidoc/en/spot/#get-deposit-list
        :param str|None code: unified currency code
        :param int 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 bitget api endpoint
        :param str|None params['pageNo']: pageNo default 1
        :param str|None params['pageSize']: pageSize default 20. Max 100
        :returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        await self.load_markets()
        if code is None:
            raise ArgumentsRequired(self.id + ' fetchDeposits() requires a `code` argument')
        currency = self.currency(code)
        if since is None:
            since = self.milliseconds() - 31556952000  # 1yr
        request = {
            'coin': currency['code'],
            'startTime': since,
            'endTime': self.milliseconds(),
        }
        if limit is not None:
            request['pageSize'] = limit
        response = await self.privateSpotGetWalletDepositList(self.extend(request, params))
        #
        #      {
        #          "code": "00000",
        #          "msg": "success",
        #          "requestTime": 0,
        #          "data": [{
        #              "id": "925607360021839872",
        #              "txId": "f73a4ac034da06b729f49676ca8801f406a093cf90c69b16e5a1cc9080df4ccb",
        #              "coin": "USDT",
        #              "type": "deposit",
        #              "amount": "19.44800000",
        #              "status": "success",
        #              "toAddress": "TRo4JMfZ1XYHUgnLsUMfDEf8MWzcWaf8uh",
        #              "fee": null,
        #              "chain": "TRC20",
        #              "confirm": null,
        #              "cTime": "1656407912259",
        #              "uTime": "1656407940148"
        #          }]
        #      }
        #
        rawTransactions = self.safe_value(response, 'data', [])
        return self.parse_transactions(rawTransactions, currency, since, limit)

    async def withdraw(self, code, amount, address, tag=None, params={}):
        """
        make a withdrawal
        :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 bitget api endpoint
        :param str params['chain']: the chain to withdraw to
        :returns dict: a `transaction structure <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        self.check_address(address)
        chain = self.safe_string(params, 'chain')
        if chain is None:
            raise ArgumentsRequired(self.id + ' withdraw() requires a chain parameter')
        await self.load_markets()
        currency = self.currency(code)
        request = {
            'coin': currency['code'],
            'address': address,
            'chain': chain,
            'amount': amount,
        }
        if tag is not None:
            request['tag'] = tag
        response = await self.privateSpotPostWalletWithdrawal(self.extend(request, params))
        #
        #     {
        #         "code": "00000",
        #         "msg": "success",
        #         "data": "888291686266343424"
        #     }
        #
        result = {
            'id': self.safe_string(response, 'data'),
            'info': response,
            'txid': None,
            'timestamp': None,
            'datetime': None,
            'network': None,
            'addressFrom': None,
            'address': None,
            'addressTo': None,
            'amount': None,
            'type': 'withdrawal',
            'currency': None,
            'status': None,
            'updated': None,
            'tagFrom': None,
            'tag': None,
            'tagTo': None,
            'comment': None,
            'fee': None,
        }
        withdrawOptions = self.safe_value(self.options, 'withdraw', {})
        fillResponseFromRequest = self.safe_value(withdrawOptions, 'fillResponseFromRequest', True)
        if fillResponseFromRequest:
            result['currency'] = code
            result['timestamp'] = self.milliseconds()
            result['datetime'] = self.iso8601(self.milliseconds())
            result['amount'] = amount
            result['tag'] = tag
            result['address'] = address
            result['addressTo'] = address
            result['network'] = chain
        return result

    async def fetch_withdrawals(self, code=None, since=None, limit=None, params={}):
        """
        fetch all withdrawals made from an account
        see https://bitgetlimited.github.io/apidoc/en/spot/#get-withdraw-list
        :param str|None code: unified currency code
        :param int 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 bitget api endpoint
        :param str|None params['pageNo']: pageNo default 1
        :param str|None params['pageSize']: pageSize default 20. Max 100
        :returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        await self.load_markets()
        if code is None:
            raise ArgumentsRequired(self.id + ' fetchWithdrawals() requires a `code` argument')
        currency = self.currency(code)
        if since is None:
            since = self.milliseconds() - 31556952000  # 1yr
        request = {
            'coin': currency['code'],
            'startTime': since,
            'endTime': self.milliseconds(),
        }
        if limit is not None:
            request['pageSize'] = limit
        response = await self.privateSpotGetWalletWithdrawalList(self.extend(request, params))
        #
        #      {
        #          "code": "00000",
        #          "msg": "success",
        #          "requestTime": 0,
        #          "data": [{
        #              "id": "925607360021839872",
        #              "txId": "f73a4ac034da06b729f49676ca8801f406a093cf90c69b16e5a1cc9080df4ccb",
        #              "coin": "USDT",
        #              "type": "deposit",
        #              "amount": "19.44800000",
        #              "status": "success",
        #              "toAddress": "TRo4JMfZ1XYHUgnLsUMfDEf8MWzcWaf8uh",
        #              "fee": null,
        #              "chain": "TRC20",
        #              "confirm": null,
        #              "cTime": "1656407912259",
        #              "uTime": "1656407940148"
        #          }]
        #      }
        #
        rawTransactions = self.safe_value(response, 'data', [])
        return self.parse_transactions(rawTransactions, currency, since, limit)

    def parse_transaction(self, transaction, currency=None):
        #
        #     {
        #         "id": "925607360021839872",
        #         "txId": "f73a4ac034da06b729f49676ca8801f406a093cf90c69b16e5a1cc9080df4ccb",
        #         "coin": "USDT",
        #         "type": "deposit",
        #         "amount": "19.44800000",
        #         "status": "success",
        #         "toAddress": "TRo4JMfZ1XYHUgnLsUMfDEf8MWzcWaf8uh",
        #         "fee": null,
        #         "chain": "TRC20",
        #         "confirm": null,
        #         "cTime": "1656407912259",
        #         "uTime": "1656407940148"
        #     }
        #
        timestamp = self.safe_integer(transaction, 'cTime')
        networkId = self.safe_string(transaction, 'chain')
        currencyId = self.safe_string(transaction, 'coin')
        status = self.safe_string(transaction, 'status')
        return {
            'id': self.safe_string(transaction, 'id'),
            'info': transaction,
            'txid': self.safe_string(transaction, 'txId'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'network': networkId,
            'addressFrom': None,
            'address': self.safe_string(transaction, 'toAddress'),
            'addressTo': self.safe_string(transaction, 'toAddress'),
            'amount': self.safe_number(transaction, 'amount'),
            'type': self.safe_string(transaction, 'type'),
            'currency': self.safe_currency_code(currencyId),
            'status': self.parse_transaction_status(status),
            'updated': self.safe_number(transaction, 'uTime'),
            'tagFrom': None,
            'tag': None,
            'tagTo': None,
            'comment': None,
            'fee': None,
        }

    def parse_transaction_status(self, status):
        statuses = {
            'success': 'ok',
            'Pending': 'pending',
            'pending_review': 'pending',
            'pending_review_fail': 'failed',
            'reject': 'failed',
        }
        return self.safe_string(statuses, status, status)

    async def fetch_deposit_address(self, code, params={}):
        """
        fetch the deposit address for a currency associated with self account
        :param str code: unified currency code
        :param dict params: extra parameters specific to the bitget api endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/en/latest/manual.html#address-structure>`
        """
        await self.load_markets()
        networkCode = self.safe_string(params, 'network')
        networkId = self.network_code_to_id(networkCode, code)
        currency = self.currency(code)
        request = {
            'coin': currency['code'],
        }
        if networkId is not None:
            request['chain'] = networkId
        response = await self.privateSpotGetWalletDepositAddress(self.extend(request, params))
        #
        #     {
        #         "code": "00000",
        #         "msg": "success",
        #         "data": {
        #             "address": "1HPn8Rx2y6nNSfagQBKy27GB99Vbzg89wv",
        #             "chain": "BTC-Bitcoin",
        #             "coin": "BTC",
        #             "tag": "",
        #             "url": "https://btc.com/1HPn8Rx2y6nNSfagQBKy27GB99Vbzg89wv"
        #         }
        #     }
        #
        data = self.safe_value(response, 'data', {})
        return self.parse_deposit_address(data, currency)

    def parse_deposit_address(self, depositAddress, currency=None):
        #
        #    {
        #        "address": "1HPn8Rx2y6nNSfagQBKy27GB99Vbzg89wv",
        #        "chain": "BTC-Bitcoin",
        #        "coin": "BTC",
        #        "tag": "",
        #        "url": "https://btc.com/1HPn8Rx2y6nNSfagQBKy27GB99Vbzg89wv"
        #    }
        #
        currencyId = self.safe_string(depositAddress, 'coin')
        networkId = self.safe_string(depositAddress, 'chain')
        parsedCurrency = self.safe_currency_code(currencyId, currency)
        return {
            'currency': parsedCurrency,
            'address': self.safe_string(depositAddress, 'address'),
            'tag': self.safe_string(depositAddress, 'tag'),
            'network': self.network_id_to_code(networkId, parsedCurrency),
            'info': depositAddress,
        }

    async 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 bitget 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
        """
        await self.load_markets()
        market = self.market(symbol)
        marketType, query = self.handle_market_type_and_params('fetchOrderBook', market, params)
        method = self.get_supported_mapping(marketType, {
            'spot': 'publicSpotGetMarketDepth',
            'swap': 'publicMixGetMarketDepth',
        })
        request = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = limit
        response = await getattr(self, method)(self.extend(request, query))
        #
        #     {
        #       code: '00000',
        #       msg: 'success',
        #       requestTime: 1645854610294,
        #       data: {
        #         asks: [['39102', '11.026']],
        #         bids: [['39100.5', '1.773']],
        #         timestamp: '1645854610294'
        #       }
        #     }
        #
        data = self.safe_value(response, 'data')
        timestamp = self.safe_integer(data, 'timestamp')
        return self.parse_order_book(data, symbol, timestamp)

    def parse_ticker(self, ticker, market=None):
        #
        # spot
        #
        #     {
        #         symbol: 'BTCUSDT',
        #         high24h: '40252.43',
        #         low24h: '38548.54',
        #         close: '39102.16',
        #         quoteVol: '67295596.1458',
        #         baseVol: '1723.4152',
        #         usdtVol: '67295596.14578',
        #         ts: '1645856170030',
        #         buyOne: '39096.16',
        #         sellOne: '39103.99'
        #     }
        #
        # swap
        #
        #     {
        #         symbol: 'BTCUSDT_UMCBL',
        #         last: '39086',
        #         bestAsk: '39087',
        #         bestBid: '39086',
        #         high24h: '40312',
        #         low24h: '38524.5',
        #         timestamp: '1645856591864',
        #         priceChangePercent: '-0.00861',
        #         baseVolume: '142251.757',
        #         quoteVolume: '5552388715.9215',
        #         usdtVolume: '5552388715.9215'
        #     }
        #
        marketId = self.safe_string(ticker, 'symbol')
        if (market is None) and (marketId is not None) and (marketId.find('_') == -1):
            # fetchTickers fix:
            # spot symbol are different from the "request id"
            # so we need to convert it to the exchange-specific id
            # otherwise we will not be able to find the market
            marketId = marketId + '_SPBL'
        symbol = self.safe_symbol(marketId, market)
        high = self.safe_string(ticker, 'high24h')
        low = self.safe_string(ticker, 'low24h')
        close = self.safe_string_2(ticker, 'close', 'last')
        quoteVolume = self.safe_string_2(ticker, 'quoteVol', 'quoteVolume')
        baseVolume = self.safe_string_2(ticker, 'baseVol', 'baseVolume')
        timestamp = self.safe_integer_2(ticker, 'ts', 'timestamp')
        datetime = self.iso8601(timestamp)
        bid = self.safe_string_2(ticker, 'buyOne', 'bestBid')
        ask = self.safe_string_2(ticker, 'sellOne', 'bestAsk')
        percentage = Precise.string_mul(self.safe_string(ticker, 'priceChangePercent'), '100')
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': datetime,
            'high': high,
            'low': low,
            'bid': bid,
            'bidVolume': None,
            'ask': ask,
            'askVolume': None,
            'vwap': None,
            'open': None,
            'close': close,
            'last': None,
            'previousClose': None,
            'change': None,
            'percentage': percentage,
            'average': None,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        }, market)

    async 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 bitget api endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        marketType, query = self.handle_market_type_and_params('fetchTicker', market, params)
        method = self.get_supported_mapping(marketType, {
            'spot': 'publicSpotGetMarketTicker',
            'swap': 'publicMixGetMarketTicker',
        })
        response = await getattr(self, method)(self.extend(request, query))
        #
        #     {
        #         code: '00000',
        #         msg: 'success',
        #         requestTime: '1645856138576',
        #         data: {
        #             symbol: 'BTCUSDT',
        #             high24h: '40252.43',
        #             low24h: '38548.54',
        #             close: '39104.65',
        #             quoteVol: '67221762.2184',
        #             baseVol: '1721.527',
        #             usdtVol: '67221762.218361',
        #             ts: '1645856138031',
        #             buyOne: '39102.55',
        #             sellOne: '39110.56'
        #         }
        #     }
        #
        data = self.safe_value(response, 'data')
        return self.parse_ticker(data, market)

    async 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
        see https://bitgetlimited.github.io/apidoc/en/spot/#get-all-tickers
        see https://bitgetlimited.github.io/apidoc/en/mix/#get-all-symbol-ticker
        :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 bitget api endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
        """
        sandboxMode = self.safe_value(self.options, 'sandboxMode', False)
        await self.load_markets()
        type = None
        market = None
        if symbols is not None:
            symbol = self.safe_value(symbols, 0)
            market = self.market(symbol)
        type, params = self.handle_market_type_and_params('fetchTickers', market, params)
        method = self.get_supported_mapping(type, {
            'spot': 'publicSpotGetMarketTickers',
            'swap': 'publicMixGetMarketTickers',
        })
        request = {}
        if method == 'publicMixGetMarketTickers':
            subType = None
            subType, params = self.handle_sub_type_and_params('fetchTickers', None, params)
            productType = 'UMCBL' if (subType == 'linear') else 'DMCBL'
            if sandboxMode:
                productType = 'S' + productType
            request['productType'] = productType
        response = await getattr(self, method)(self.extend(request, params))
        #
        # spot
        #
        #     {
        #         "code":"00000",
        #         "msg":"success",
        #         "requestTime":1653237548496,
        #         "data":[
        #             {
        #                 "symbol":"LINKUSDT",
        #                 "high24h":"7.2634",
        #                 "low24h":"7.1697",
        #                 "close":"7.2444",
        #                 "quoteVol":"330424.2366",
        #                 "baseVol":"46401.3116",
        #                 "usdtVol":"330424.2365573",
        #                 "ts":"1653237548026",
        #                 "buyOne":"7.2382",
        #                 "sellOne":"7.2513"
        #             },
        #         ]
        #     }
        #
        # swap
        #
        #     {
        #         "code":"00000",
        #         "msg":"success",
        #         "requestTime":1653237819762,
        #         "data":[
        #             {
        #                 "symbol":"BTCUSDT_UMCBL",
        #                 "last":"29891.5",
        #                 "bestAsk":"29891.5",
        #                 "bestBid":"29889.5",
        #                 "high24h":"29941.5",
        #                 "low24h":"29737.5",
        #                 "timestamp":"1653237819761",
        #                 "priceChangePercent":"0.00163",
        #                 "baseVolume":"127937.56",
        #                 "quoteVolume":"3806276573.6285",
        #                 "usdtVolume":"3806276573.6285"
        #             },
        #         ]
        #     }
        #
        data = self.safe_value(response, 'data')
        return self.parse_tickers(data, symbols)

    def parse_trade(self, trade, market=None):
        #
        # spot
        #
        #     {
        #         symbol: 'BTCUSDT_SPBL',
        #         tradeId: '881371996363608065',
        #         side: 'sell',
        #         fillPrice: '39123.05',
        #         fillQuantity: '0.0363',
        #         fillTime: '1645861379709'
        #     }
        #
        # swap
        #
        #     {
        #         tradeId: '881373204067311617',
        #         price: '39119.0',
        #         size: '0.001',
        #         side: 'buy',
        #         timestamp: '1645861667648',
        #         symbol: 'BTCUSDT_UMCBL'
        #     }
        #
        # private
        #
        #     {
        #         accountId: '6394957606',
        #         symbol: 'LTCUSDT_SPBL',
        #         orderId: '864752115272552448',
        #         fillId: '864752115685969921',
        #         orderType: 'limit',
        #         side: 'buy',
        #         fillPrice: '127.92000000',
        #         fillQuantity: '0.10000000',
        #         fillTotalAmount: '12.79200000',
        #         feeCcy: 'LTC',
        #         fees: '0.00000000',
        #         cTime: '1641898891373'
        #     }
        #
        #     {
        #         tradeId: '881640729552281602',
        #         symbol: 'BTCUSDT_UMCBL',
        #         orderId: '881640729145409536',
        #         price: '38429.50',
        #         sizeQty: '0.001',
        #         fee: '0',
        #         side: 'open_long',
        #         fillAmount: '38.4295',
        #         profit: '0',
        #         cTime: '1645925450694'
        #     }
        #
        marketId = self.safe_string(trade, 'symbol')
        symbol = self.safe_symbol(marketId, market)
        id = self.safe_string_2(trade, 'tradeId', 'fillId')
        order = self.safe_string(trade, 'orderId')
        side = self.safe_string(trade, 'side')
        price = self.safe_string_2(trade, 'fillPrice', 'price')
        amount = self.safe_string_2(trade, 'fillQuantity', 'size')
        amount = self.safe_string(trade, 'sizeQty', amount)
        timestamp = self.safe_integer_2(trade, 'fillTime', 'timestamp')
        timestamp = self.safe_integer(trade, 'cTime', timestamp)
        fee = None
        feeAmount = self.safe_string(trade, 'fees')
        type = self.safe_string(trade, 'orderType')
        if feeAmount is not None:
            currencyCode = self.safe_currency_code(self.safe_string(trade, 'feeCcy'))
            fee = {
                'code': currencyCode,  # kept here for backward-compatibility, but will be removed soon
                'currency': currencyCode,
                'cost': feeAmount,
            }
        datetime = self.iso8601(timestamp)
        return self.safe_trade({
            'info': trade,
            'id': id,
            'order': order,
            'symbol': symbol,
            'side': side,
            'type': type,
            'takerOrMaker': None,
            'price': price,
            'amount': amount,
            'cost': None,
            'fee': fee,
            'timestamp': timestamp,
            'datetime': datetime,
        }, market)

    async def fetch_trades(self, symbol, limit=None, since=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 bitget api endpoint
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html?#public-trades>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = limit
        marketType, query = self.handle_market_type_and_params('fetchTrades', market, params)
        method = self.get_supported_mapping(marketType, {
            'spot': 'publicSpotGetMarketFills',
            'swap': 'publicMixGetMarketFills',
        })
        response = await getattr(self, method)(self.extend(request, query))
        #
        #     {
        #       code: '00000',
        #       msg: 'success',
        #       requestTime: '1645861382032',
        #       data: [
        #         {
        #           symbol: 'BTCUSDT_SPBL',
        #           tradeId: '881371996363608065',
        #           side: 'sell',
        #           fillPrice: '39123.05',
        #           fillQuantity: '0.0363',
        #           fillTime: '1645861379709'
        #         }
        #       ]
        #     }
        #
        data = self.safe_value(response, 'data', [])
        return self.parse_trades(data, market, since, limit)

    async def fetch_trading_fee(self, symbol, params={}):
        """
        fetch the trading fees for a market
        :param str symbol: unified market symbol
        :param dict params: extra parameters specific to the bitget api endpoint
        :returns dict: a `fee structure <https://docs.ccxt.com/en/latest/manual.html#fee-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = await self.publicSpotGetPublicProduct(self.extend(request, params))
        #
        #     {
        #         code: '00000',
        #         msg: 'success',
        #         requestTime: '1646255374000',
        #         data: {
        #           symbol: 'ethusdt_SPBL',
        #           symbolName: null,
        #           baseCoin: 'ETH',
        #           quoteCoin: 'USDT',
        #           minTradeAmount: '0',
        #           maxTradeAmount: '0',
        #           takerFeeRate: '0.002',
        #           makerFeeRate: '0.002',
        #           priceScale: '2',
        #           quantityScale: '4',
        #           status: 'online'
        #         }
        #     }
        #
        data = self.safe_value(response, 'data', {})
        return self.parse_trading_fee(data, market)

    async def fetch_trading_fees(self, params={}):
        """
        fetch the trading fees for multiple markets
        :param dict params: extra parameters specific to the bitget api endpoint
        :returns dict: a dictionary of `fee structures <https://docs.ccxt.com/en/latest/manual.html#fee-structure>` indexed by market symbols
        """
        await self.load_markets()
        response = await self.publicSpotGetPublicProducts(params)
        #
        #     {
        #         code: '00000',
        #         msg: 'success',
        #         requestTime: '1646255662391',
        #         data: [
        #           {
        #             symbol: 'ALPHAUSDT_SPBL',
        #             symbolName: 'ALPHAUSDT',
        #             baseCoin: 'ALPHA',
        #             quoteCoin: 'USDT',
        #             minTradeAmount: '2',
        #             maxTradeAmount: '0',
        #             takerFeeRate: '0.001',
        #             makerFeeRate: '0.001',
        #             priceScale: '4',
        #             quantityScale: '4',
        #             status: 'online'
        #           },
        #           ...
        #         ]
        #     }
        #
        data = self.safe_value(response, 'data', [])
        result = {}
        for i in range(0, len(data)):
            feeInfo = data[i]
            fee = self.parse_trading_fee(feeInfo)
            symbol = fee['symbol']
            result[symbol] = fee
        return result

    def parse_trading_fee(self, data, market=None):
        marketId = self.safe_string(data, 'symbol')
        return {
            'info': data,
            'symbol': self.safe_symbol(marketId, market),
            'maker': self.safe_number(data, 'makerFeeRate'),
            'taker': self.safe_number(data, 'takerFeeRate'),
        }

    def parse_ohlcv(self, ohlcv, market=None, timeframe='1m'):
        #
        # spot
        #
        #     {
        #         open: '57882.31',
        #         high: '58967.24',
        #         low: '57509.56',
        #         close: '57598.96',
        #         quoteVol: '439160536.605821',
        #         baseVol: '7531.2927',
        #         usdtVol: '439160536.605821',
        #         ts: '1637337600000'
        #     }
        #
        # swap
        #
        #     [
        #         "1645911960000",
        #         "39406",
        #         "39407",
        #         "39374.5",
        #         "39379",
        #         "35.526",
        #         "1399132.341"
        #     ]
        #
        return [
            self.safe_integer_2(ohlcv, 0, 'ts'),
            self.safe_number_2(ohlcv, 1, 'open'),
            self.safe_number_2(ohlcv, 2, 'high'),
            self.safe_number_2(ohlcv, 3, 'low'),
            self.safe_number_2(ohlcv, 4, 'close'),
            self.safe_number_2(ohlcv, 5, 'baseVol'),
        ]

    async 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 bitget api endpoint
        :param int|None params['until']: timestamp in ms of the latest candle to fetch
        :returns [[int]]: A list of candles ordered as timestamp, open, high, low, close, volume
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        marketType, query = self.handle_market_type_and_params('fetchOHLCV', market, params)
        method = self.get_supported_mapping(marketType, {
            'spot': 'publicSpotGetMarketCandles',
            'swap': 'publicMixGetMarketCandles',
        })
        until = self.safe_integer_2(query, 'until', 'till')
        if limit is None:
            limit = 100
        if market['type'] == 'spot':
            timeframes = self.options['timeframes']['spot']
            request['period'] = self.safe_string(timeframes, timeframe, timeframe)
            request['limit'] = limit
            if since is not None:
                request['after'] = since
                if until is None:
                    millisecondsPerTimeframe = self.options['timeframes']['swap'][timeframe] * 1000
                    request['before'] = self.sum(since, millisecondsPerTimeframe * limit)
            if until is not None:
                request['before'] = until
        elif market['type'] == 'swap':
            timeframes = self.options['timeframes']['swap']
            request['granularity'] = self.safe_string(timeframes, timeframe, timeframe)
            duration = self.parse_timeframe(timeframe)
            now = self.milliseconds()
            if since is None:
                request['startTime'] = now - (limit - 1) * (duration * 1000)
                request['endTime'] = now
            else:
                request['startTime'] = self.sum(since, duration * 1000)
                if until is not None:
                    request['endTime'] = until
                else:
                    request['endTime'] = self.sum(since, limit * duration * 1000)
        ommitted = self.omit(query, ['until', 'till'])
        response = await getattr(self, method)(self.extend(request, ommitted))
        #  [["1645911960000","39406","39407","39374.5","39379","35.526","1399132.341"]]
        data = self.safe_value(response, 'data', response)
        return self.parse_ohlcvs(data, market, timeframe, since, limit)

    async def fetch_balance(self, params={}):
        """
        query for balance and get the amount of funds available for trading or funds locked in orders
        :param dict params: extra parameters specific to the bitget api endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/en/latest/manual.html?#balance-structure>`
        """
        sandboxMode = self.safe_value(self.options, 'sandboxMode', False)
        await self.load_markets()
        marketType, query = self.handle_market_type_and_params('fetchBalance', None, params)
        method = self.get_supported_mapping(marketType, {
            'spot': 'privateSpotGetAccountAssets',
            'swap': 'privateMixGetAccountAccounts',
        })
        request = {}
        if marketType == 'swap':
            subType = None
            subType, params = self.handle_sub_type_and_params('fetchBalance', None, params)
            productType = 'UMCBL' if (subType == 'linear') else 'DMCBL'
            if sandboxMode:
                productType = 'S' + productType
            request['productType'] = productType
        response = await getattr(self, method)(self.extend(request, query))
        # spot
        #     {
        #       code: '00000',
        #       msg: 'success',
        #       requestTime: 1645928868827,
        #       data: [
        #         {
        #           coinId: 1,
        #           coinName: 'BTC',
        #           available: '0.00070000',
        #           frozen: '0.00000000',
        #           lock: '0.00000000',
        #           uTime: '1645921706000'
        #         }
        #       ]
        #     }
        #
        # swap
        #     {
        #       code: '00000',
        #       msg: 'success',
        #       requestTime: 1645928929251,
        #       data: [
        #         {
        #           marginCoin: 'USDT',
        #           locked: '0',
        #           available: '8.078525',
        #           crossMaxAvailable: '8.078525',
        #           fixedMaxAvailable: '8.078525',
        #           maxTransferOut: '8.078525',
        #           equity: '10.02508',
        #           usdtEquity: '10.02508',
        #           btcEquity: '0.00026057027'
        #         }
        #       ]
        #     }
        data = self.safe_value(response, 'data')
        return self.parse_balance(data)

    def parse_balance(self, balance):
        result = {'info': balance}
        #
        #     {
        #       coinId: '1',
        #       coinName: 'BTC',
        #       available: '0.00099900',
        #       frozen: '0.00000000',
        #       lock: '0.00000000',
        #       uTime: '1661595535000'
        #     }
        #
        for i in range(0, len(balance)):
            entry = balance[i]
            currencyId = self.safe_string_2(entry, 'coinName', 'marginCoin')
            code = self.safe_currency_code(currencyId)
            account = self.account()
            frozen = self.safe_string(entry, 'frozen')
            locked = self.safe_string_2(entry, 'lock', 'locked')
            account['used'] = Precise.string_add(frozen, locked)
            account['free'] = self.safe_string(entry, 'available')
            result[code] = account
        return self.safe_balance(result)

    def parse_order_status(self, status):
        statuses = {
            'new': 'open',
            'init': 'open',
            'not_trigger': 'open',
            'triggered': 'closed',
            'full_fill': 'closed',
            'filled': 'closed',
            'fail_trigger': 'canceled',
            'cancel': 'canceled',
            'cancelled': 'canceled',
            'canceled': 'canceled',
        }
        return self.safe_string(statuses, status, status)

    def parse_order(self, order, market=None):
        #
        # spot
        #     {
        #       accountId: '6394957606',
        #       symbol: 'BTCUSDT_SPBL',
        #       orderId: '881623995442958336',
        #       clientOrderId: '135335e9-b054-4e43-b00a-499f11d3a5cc',
        #       price: '39000.000000000000',
        #       quantity: '0.000700000000',
        #       orderType: 'limit',
        #       side: 'buy',
        #       status: 'new',
        #       fillPrice: '0.000000000000',
        #       fillQuantity: '0.000000000000',
        #       fillTotalAmount: '0.000000000000',
        #       cTime: '1645921460972'
        #     }
        #
        # swap
        #     {
        #       symbol: 'BTCUSDT_UMCBL',
        #       size: 0.001,
        #       orderId: '881640729145409536',
        #       clientOid: '881640729204129792',
        #       filledQty: 0.001,
        #       fee: 0,
        #       price: null,
        #       priceAvg: 38429.5,
        #       state: 'filled',
        #       side: 'open_long',
        #       timeInForce: 'normal',
        #       totalProfits: 0,
        #       posSide: 'long',
        #       marginCoin: 'USDT',
        #       filledAmount: 38.4295,
        #       orderType: 'market',
        #       cTime: '1645925450611',
        #       uTime: '1645925450746'
        #     }
        #
        # stop
        #
        #     {
        #         "orderId": "910246821491617792",
        #         "symbol": "BTCUSDT_UMCBL",
        #         "marginCoin": "USDT",
        #         "size": "16",
        #         "executePrice": "20000",
        #         "triggerPrice": "24000",
        #         "status": "not_trigger",
        #         "orderType": "limit",
        #         "planType": "normal_plan",
        #         "side": "open_long",
        #         "triggerType": "market_price",
        #         "presetTakeProfitPrice": "0",
        #         "presetTakeLossPrice": "0",
        #         "cTime": "1652745674488"
        #     }
        #
        marketId = self.safe_string(order, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = market['symbol']
        id = self.safe_string(order, 'orderId')
        price = self.safe_string_2(order, 'price', 'executePrice')
        amount = self.safe_string_2(order, 'quantity', 'size')
        filled = self.safe_string_2(order, 'fillQuantity', 'filledQty')
        cost = self.safe_string_2(order, 'fillTotalAmount', 'filledAmount')
        average = self.safe_string_2(order, 'fillPrice', 'priceAvg')
        type = self.safe_string(order, 'orderType')
        timestamp = self.safe_integer(order, 'cTime')
        side = self.safe_string_2(order, 'side', 'posSide')
        if (side == 'open_long') or (side == 'close_short'):
            side = 'buy'
        elif (side == 'close_long') or (side == 'open_short'):
            side = 'sell'
        clientOrderId = self.safe_string_2(order, 'clientOrderId', 'clientOid')
        fee = None
        rawStatus = self.safe_string_2(order, 'status', 'state')
        status = self.parse_order_status(rawStatus)
        lastTradeTimestamp = self.safe_integer(order, 'uTime')
        return self.safe_order({
            'info': order,
            'id': id,
            'clientOrderId': clientOrderId,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': lastTradeTimestamp,
            'symbol': symbol,
            'type': type,
            'timeInForce': None,
            'postOnly': None,
            'side': side,
            'price': price,
            'stopPrice': self.safe_number(order, 'triggerPrice'),
            'triggerPrice': self.safe_number(order, 'triggerPrice'),
            'average': average,
            'cost': cost,
            'amount': amount,
            'filled': filled,
            'remaining': None,
            'status': status,
            'fee': fee,
            'trades': None,
        }, market)

    async 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 bitget api endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        marketType, query = self.handle_market_type_and_params('createOrder', market, params)
        request = {
            'symbol': market['id'],
            'orderType': type,
        }
        isMarketOrder = type == 'market'
        triggerPrice = self.safe_value_2(params, 'stopPrice', 'triggerPrice')
        isTriggerOrder = triggerPrice is not None
        stopLossPrice = self.safe_value(params, 'stopLossPrice')
        isStopLossOrder = stopLossPrice is not None
        takeProfitPrice = self.safe_value(params, 'takeProfitPrice')
        isTakeProfitOrder = takeProfitPrice is not None
        isStopLossOrTakeProfit = isStopLossOrder or isTakeProfitOrder
        if self.sum(isTriggerOrder, isStopLossOrder, isTakeProfitOrder) > 1:
            raise ExchangeError(self.id + ' createOrder() params can only contain one of triggerPrice, stopLossPrice, takeProfitPrice')
        if (type == 'limit') and (triggerPrice is None):
            request['price'] = self.price_to_precision(symbol, price)
        clientOrderId = self.safe_string_2(params, 'clientOid', 'clientOrderId')
        method = self.get_supported_mapping(marketType, {
            'spot': 'privateSpotPostTradeOrders',
            'swap': 'privateMixPostOrderPlaceOrder',
        })
        exchangeSpecificParam = self.safe_string_2(params, 'force', 'timeInForceValue')
        postOnly = self.is_post_only(isMarketOrder, exchangeSpecificParam == 'post_only', params)
        if marketType == 'spot':
            if isStopLossOrTakeProfit:
                raise InvalidOrder(self.id + ' createOrder() does not support stop loss/take profit orders on spot markets, only swap markets')
            timeInForceKey = 'force'
            quantityKey = 'quantity'
            quantity = None
            createMarketBuyOrderRequiresPrice = self.safe_value(self.options, 'createMarketBuyOrderRequiresPrice', True)
            if createMarketBuyOrderRequiresPrice and isMarketOrder and (side == 'buy'):
                if price is None:
                    raise InvalidOrder(self.id + ' createOrder() requires price argument for market buy orders on spot markets to calculate the total amount to spend(amount * price), alternatively set the createMarketBuyOrderRequiresPrice option to False and pass in the cost to spend into the amount parameter')
                else:
                    amountString = self.number_to_string(amount)
                    priceString = self.number_to_string(price)
                    cost = self.parse_number(Precise.string_mul(amountString, priceString))
                    quantity = self.price_to_precision(symbol, cost)
            else:
                quantity = self.amount_to_precision(symbol, amount)
            if clientOrderId is not None:
                request['clientOrderId'] = clientOrderId
            request['side'] = side
            if triggerPrice is not None:
                quantityKey = 'size'
                timeInForceKey = 'timeInForceValue'
                # default triggerType to market price for unification
                triggerType = self.safe_string(params, 'triggerType', 'market_price')
                request['triggerType'] = triggerType
                request['triggerPrice'] = self.price_to_precision(symbol, triggerPrice)
                request['executePrice'] = self.price_to_precision(symbol, price)
                method = 'privateSpotPostPlanPlacePlan'
            if quantity is not None:
                request[quantityKey] = quantity
            if postOnly:
                request[timeInForceKey] = 'post_only'
            else:
                request[timeInForceKey] = 'normal'
        else:
            if clientOrderId is not None:
                request['clientOid'] = clientOrderId
            request['size'] = self.amount_to_precision(symbol, amount)
            if postOnly:
                request['timeInForceValue'] = 'post_only'
            reduceOnly = self.safe_value(params, 'reduceOnly', False)
            if triggerPrice is not None:
                # default triggerType to market price for unification
                triggerType = self.safe_string(params, 'triggerType', 'market_price')
                request['triggerType'] = triggerType
                request['triggerPrice'] = self.price_to_precision(symbol, triggerPrice)
                if price is not None:
                    request['executePrice'] = self.price_to_precision(symbol, price)
                method = 'privateMixPostPlanPlacePlan'
            if isStopLossOrTakeProfit:
                if not isMarketOrder:
                    raise ExchangeError(self.id + ' createOrder() bitget stopLoss or takeProfit orders must be market orders')
                if isStopLossOrder:
                    request['triggerPrice'] = self.price_to_precision(symbol, stopLossPrice)
                    request['planType'] = 'loss_plan'
                elif isTakeProfitOrder:
                    request['triggerPrice'] = self.price_to_precision(symbol, takeProfitPrice)
                    request['planType'] = 'profit_plan'
                request['holdSide'] = 'long' if (side == 'buy') else 'short'
                method = 'privateMixPostPlanPlaceTPSL'
            else:
                if reduceOnly:
                    request['side'] = 'close_short' if (side == 'buy') else 'close_long'
                else:
                    request['side'] = 'open_long' if (side == 'buy') else 'open_short'
            request['marginCoin'] = market['settleId']
        omitted = self.omit(query, ['stopPrice', 'triggerType', 'stopLossPrice', 'takeProfitPrice', 'postOnly'])
        response = await getattr(self, method)(self.extend(request, omitted))
        #
        #     {
        #         "code": "00000",
        #         "msg": "success",
        #         "requestTime": 1645932209602,
        #         "data": {
        #             "orderId": "881669078313766912",
        #             "clientOrderId": "iauIBf#a45b595f96474d888d0ada"
        #         }
        #     }
        #
        data = self.safe_value(response, 'data')
        return self.parse_order(data, market)

    async def edit_order(self, id, symbol, type, side, amount, price=None, params={}):
        """
        edit a trade order
        :param str id: cancel order id
        :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 base currency, ignored in market orders
        :param dict params: extra parameters specific to the bitget api endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        marketType, query = self.handle_market_type_and_params('editOrder', market, params)
        request = {
            'orderId': id,
            'orderType': type,
        }
        isMarketOrder = type == 'market'
        triggerPrice = self.safe_value_2(params, 'stopPrice', 'triggerPrice')
        isTriggerOrder = triggerPrice is not None
        stopLossPrice = self.safe_value(params, 'stopLossPrice')
        isStopLossOrder = stopLossPrice is not None
        takeProfitPrice = self.safe_value(params, 'takeProfitPrice')
        isTakeProfitOrder = takeProfitPrice is not None
        isStopOrder = isStopLossOrder or isTakeProfitOrder
        if self.sum(isTriggerOrder, isStopLossOrder, isTakeProfitOrder) > 1:
            raise ExchangeError(self.id + ' editOrder() params can only contain one of triggerPrice, stopLossPrice, takeProfitPrice')
        if not isStopOrder and not isTriggerOrder:
            raise InvalidOrder(self.id + ' editOrder() only support plan orders')
        method = self.get_supported_mapping(marketType, {
            'spot': 'privateSpotPostPlanModifyPlan',
            'swap': 'privateMixPostPlanModifyPlan',
        })
        if triggerPrice is not None:
            # default triggerType to market price for unification
            triggerType = self.safe_string(params, 'triggerType', 'market_price')
            request['triggerType'] = triggerType
            request['triggerPrice'] = self.price_to_precision(symbol, triggerPrice)
            request['executePrice'] = self.price_to_precision(symbol, price)
        if marketType == 'spot':
            if isStopOrder:
                raise InvalidOrder(self.id + ' editOrder() does not support stop orders on spot markets, only swap markets')
            editMarketBuyOrderRequiresPrice = self.safe_value(self.options, 'editMarketBuyOrderRequiresPrice', True)
            if editMarketBuyOrderRequiresPrice and isMarketOrder and (side == 'buy'):
                if price is None:
                    raise InvalidOrder(self.id + ' editOrder() requires price argument for market buy orders on spot markets to calculate the total amount to spend(amount * price), alternatively set the editMarketBuyOrderRequiresPrice option to False and pass in the cost to spend into the amount parameter')
                else:
                    amountString = self.number_to_string(amount)
                    priceString = self.number_to_string(price)
                    cost = self.parse_number(Precise.string_mul(amountString, priceString))
                    request['size'] = self.price_to_precision(symbol, cost)
            else:
                request['size'] = self.amount_to_precision(symbol, amount)
        else:
            request['symbol'] = market['id']
            request['size'] = self.amount_to_precision(symbol, amount)
            if isStopOrder:
                if not isMarketOrder:
                    raise ExchangeError(self.id + ' editOrder() bitget stopLoss or takeProfit orders must be market orders')
                if isStopLossOrder:
                    request['triggerPrice'] = self.price_to_precision(symbol, stopLossPrice)
                    request['planType'] = 'loss_plan'
                elif isTakeProfitOrder:
                    request['triggerPrice'] = self.price_to_precision(symbol, takeProfitPrice)
                    request['planType'] = 'profit_plan'
                method = 'privateMixPostPlanModifyTPSLPlan'
            request['marginCoin'] = market['settleId']
        omitted = self.omit(query, ['stopPrice', 'triggerType', 'stopLossPrice', 'takeProfitPrice'])
        response = await getattr(self, method)(self.extend(request, omitted))
        #
        # spot
        #     {
        #         "code": "00000",
        #         "msg": "success",
        #         "requestTime": 1668136575920,
        #         "data": {
        #         "orderId": "974792060738441216",
        #         "clientOrderId": "974792554995224576"
        #         }
        #     }
        #
        data = self.safe_value(response, 'data')
        return self.parse_order(data, market)

    async def cancel_order(self, id, symbol=None, params={}):
        """
        cancels an open order
        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict params: extra parameters specific to the bitget api endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.check_required_symbol('cancelOrder', symbol)
        await self.load_markets()
        market = self.market(symbol)
        marketType, query = self.handle_market_type_and_params('cancelOrder', market, params)
        method = self.get_supported_mapping(marketType, {
            'spot': 'privateSpotPostTradeCancelOrder',
            'swap': 'privateMixPostOrderCancelOrder',
        })
        request = {
            'symbol': market['id'],
            'orderId': id,
        }
        stop = self.safe_value(query, 'stop')
        if stop:
            if marketType == 'spot':
                method = 'privateSpotPostPlanCancelPlan'
            else:
                planType = self.safe_string(params, 'planType')
                if planType is None:
                    raise ArgumentsRequired(self.id + ' cancelOrder() requires a planType parameter for stop orders, either normal_plan, profit_plan or loss_plan')
                request['planType'] = planType
                method = 'privateMixPostPlanCancelPlan'
        if marketType == 'swap':
            request['marginCoin'] = market['settleId']
        ommitted = self.omit(query, ['stop', 'planType'])
        response = await getattr(self, method)(self.extend(request, ommitted))
        return self.parse_order(response, market)

    async def cancel_orders(self, ids, symbol=None, params={}):
        """
        cancel multiple orders
        :param [str] ids: order ids
        :param str symbol: unified market symbol, default is None
        :param dict params: extra parameters specific to the bitget api endpoint
        :returns dict: an list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.check_required_symbol('cancelOrders', symbol)
        await self.load_markets()
        market = self.market(symbol)
        type = self.safe_string(params, 'type', market['type'])
        if type is None:
            raise ArgumentsRequired(self.id + " cancelOrders() requires a type parameter(one of 'spot', 'swap').")
        params = self.omit(params, 'type')
        request = {}
        method = None
        if type == 'spot':
            method = 'apiPostOrderOrdersBatchcancel'
            request['method'] = 'batchcancel'
            jsonIds = self.json(ids)
            parts = jsonIds.split('"')
            request['order_ids'] = ''.join(parts)
        elif type == 'swap':
            method = 'privateMixPostOrderCancelBatchOrders'
            request['symbol'] = market['id']
            request['marginCoin'] = market['quote']
            request['orderIds'] = ids
        response = await getattr(self, method)(self.extend(request, params))
        #
        #     spot
        #
        #     {
        #         "status": "ok",
        #         "data": {
        #             "success": [
        #                 "673451224205135872",
        #             ],
        #             "failed": [
        #                 {
        #                 "err-msg": "invalid record",
        #                 "order-id": "673451224205135873",
        #                 "err-code": "base record invalid"
        #                 }
        #             ]
        #         }
        #     }
        #
        #     swap
        #
        #     {
        #         "result":true,
        #         "symbol":"cmt_btcusdt",
        #         "order_ids":[
        #             "258414711",
        #             "478585558"
        #         ],
        #         "fail_infos":[
        #             {
        #                 "order_id":"258414711",
        #                 "err_code":"401",
        #                 "err_msg":""
        #             }
        #         ]
        #     }
        #
        return response

    async def cancel_all_orders(self, symbol=None, params={}):
        """
        cancel all open orders
        see https://bitgetlimited.github.io/apidoc/en/mix/#cancel-all-order
        see https://bitgetlimited.github.io/apidoc/en/mix/#cancel-all-trigger-order-tpsl
        :param str|None symbol: unified market symbol
        :param dict params: extra parameters specific to the bitget api endpoint
        :param str params['code']: marginCoin unified currency code
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        sandboxMode = self.safe_value(self.options, 'sandboxMode', False)
        await self.load_markets()
        market = None
        if symbol is not None:
            market = self.market(symbol)
        subType = None
        subType, params = self.handle_sub_type_and_params('cancelAllOrders', market, params)
        productType = 'UMCBL' if (subType == 'linear') else 'DMCBL'
        if sandboxMode:
            productType = 'S' + productType
        marketType, query = self.handle_market_type_and_params('cancelAllOrders', market, params)
        if marketType == 'spot':
            raise NotSupported(self.id + ' cancelAllOrders() does not support spot markets')
        request = {
            'productType': productType,
        }
        method = None
        stop = self.safe_value(query, 'stop')
        planType = self.safe_string(query, 'planType')
        if stop is not None or planType is not None:
            if planType is None:
                raise ArgumentsRequired(self.id + ' cancelOrder() requires a planType parameter for stop orders, either normal_plan, profit_plan, loss_plan, pos_profit, pos_loss, moving_plan or track_plan')
            method = 'privateMixPostPlanCancelAllPlan'
        else:
            code = self.safe_string_2(params, 'code', 'marginCoin')
            if code is None:
                raise ArgumentsRequired(self.id + ' cancelAllOrders() requires a code argument [marginCoin] in the params')
            currency = self.currency(code)
            request['marginCoin'] = self.safe_currency_code(code, currency)
            method = 'privateMixPostOrderCancelAllOrders'
        ommitted = self.omit(query, ['stop', 'code', 'marginCoin'])
        response = await getattr(self, method)(self.extend(request, ommitted))
        #
        #     {
        #         "code": "00000",
        #         "msg": "success",
        #         "requestTime": 1663312535998,
        #         "data": {
        #             "result": True,
        #             "order_ids": ["954564352813969409"],
        #             "fail_infos": [
        #                 {
        #                     "order_id": "",
        #                     "err_code": "",
        #                     "err_msg": ""
        #                 }
        #             ]
        #         }
        #     }
        #
        return response

    async 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 bitget api endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.check_required_symbol('fetchOrder', symbol)
        await self.load_markets()
        market = self.market(symbol)
        marketType, query = self.handle_market_type_and_params('fetchOrder', market, params)
        method = self.get_supported_mapping(marketType, {
            'spot': 'privateSpotPostTradeOrderInfo',
            'swap': 'privateMixGetOrderDetail',
        })
        request = {
            'symbol': market['id'],
            'orderId': id,
        }
        response = await getattr(self, method)(self.extend(request, query))
        # spot
        #     {
        #       code: '00000',
        #       msg: 'success',
        #       requestTime: '1645926849436',
        #       data: [
        #         {
        #           accountId: '6394957606',
        #           symbol: 'BTCUSDT_SPBL',
        #           orderId: '881626139738935296',
        #           clientOrderId: '525890c8-767e-4cd6-8585-38160ed7bb5e',
        #           price: '38000.000000000000',
        #           quantity: '0.000700000000',
        #           orderType: 'limit',
        #           side: 'buy',
        #           status: 'new',
        #           fillPrice: '0.000000000000',
        #           fillQuantity: '0.000000000000',
        #           fillTotalAmount: '0.000000000000',
        #           cTime: '1645921972212'
        #         }
        #       ]
        #     }
        #
        # swap
        #     {
        #       code: '00000',
        #       msg: 'success',
        #       requestTime: '1645926587877',
        #       data: {
        #         symbol: 'BTCUSDT_UMCBL',
        #         size: '0.001',
        #         orderId: '881640729145409536',
        #         clientOid: '881640729204129792',
        #         filledQty: '0.001',
        #         fee: '0E-8',
        #         price: null,
        #         priceAvg: '38429.50',
        #         state: 'filled',
        #         side: 'open_long',
        #         timeInForce: 'normal',
        #         totalProfits: '0E-8',
        #         posSide: 'long',
        #         marginCoin: 'USDT',
        #         filledAmount: '38.4295',
        #         orderType: 'market',
        #         cTime: '1645925450611',
        #         uTime: '1645925450746'
        #       }
        #     }
        #
        data = self.safe_value(response, 'data')
        first = self.safe_value(data, 0, data)
        return self.parse_order(first, market)

    async def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
        """
        fetch all unfilled currently open orders
        :param str 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 order structures to retrieve
        :param dict params: extra parameters specific to the bitget api endpoint
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.check_required_symbol('fetchOpenOrders', symbol)
        await self.load_markets()
        market = self.market(symbol)
        marketType = None
        query = None
        marketType, query = self.handle_market_type_and_params('fetchOpenOrders', market, params)
        request = {
            'symbol': market['id'],
        }
        method = self.get_supported_mapping(marketType, {
            'spot': 'privateSpotPostTradeOpenOrders',
            'swap': 'privateMixGetOrderCurrent',
        })
        stop = self.safe_value(query, 'stop')
        if stop:
            if marketType == 'spot':
                method = 'privateSpotPostPlanCurrentPlan'
                if limit is not None:
                    request['pageSize'] = limit
            else:
                method = 'privateMixGetPlanCurrentPlan'
            query = self.omit(query, 'stop')
        response = await getattr(self, method)(self.extend(request, query))
        #
        #  spot
        #     {
        #       code: '00000',
        #       msg: 'success',
        #       requestTime: 1645921640193,
        #       data: [
        #         {
        #           accountId: '6394957606',
        #           symbol: 'BTCUSDT_SPBL',
        #           orderId: '881623995442958336',
        #           clientOrderId: '135335e9-b054-4e43-b00a-499f11d3a5cc',
        #           price: '39000.000000000000',
        #           quantity: '0.000700000000',
        #           orderType: 'limit',
        #           side: 'buy',
        #           status: 'new',
        #           fillPrice: '0.000000000000',
        #           fillQuantity: '0.000000000000',
        #           fillTotalAmount: '0.000000000000',
        #           cTime: '1645921460972'
        #         }
        #       ]
        #     }
        #
        # swap
        #     {
        #       code: '00000',
        #       msg: 'success',
        #       requestTime: 1645922324630,
        #       data: [
        #         {
        #           symbol: 'BTCUSDT_UMCBL',
        #           size: 0.001,
        #           orderId: '881627074081226752',
        #           clientOid: '881627074160918528',
        #           filledQty: 0,
        #           fee: 0,
        #           price: 38000,
        #           state: 'new',
        #           side: 'open_long',
        #           timeInForce: 'normal',
        #           totalProfits: 0,
        #           posSide: 'long',
        #           marginCoin: 'USDT',
        #           filledAmount: 0,
        #           orderType: 'limit',
        #           cTime: '1645922194995',
        #           uTime: '1645922194995'
        #         }
        #       ]
        #     }
        #
        # stop
        #
        #     {
        #         "code": "00000",
        #         "msg": "success",
        #         "requestTime": 1652745815697,
        #         "data": [
        #             {
        #                 "orderId": "910246821491617792",
        #                 "symbol": "BTCUSDT_UMCBL",
        #                 "marginCoin": "USDT",
        #                 "size": "16",
        #                 "executePrice": "20000",
        #                 "triggerPrice": "24000",
        #                 "status": "not_trigger",
        #                 "orderType": "limit",
        #                 "planType": "normal_plan",
        #                 "side": "open_long",
        #                 "triggerType": "market_price",
        #                 "presetTakeProfitPrice": "0",
        #                 "presetTakeLossPrice": "0",
        #                 "cTime": "1652745674488"
        #             }
        #         ]
        #     }
        #
        # spot plan order
        #
        #     {
        #         "code": "00000",
        #         "msg": "success",
        #         "requestTime": 1668134581006,
        #         "data": {
        #             "nextFlag": False,
        #             "endId": 974792555020390400,
        #             "orderList": [{
        #                 "orderId": "974792555020390400",
        #                 "symbol": "TRXUSDT_SPBL",
        #                 "size": "151",
        #                 "executePrice": "0.041572",
        #                 "triggerPrice": "0.041572",
        #                 "status": "not_trigger",
        #                 "orderType": "limit",
        #                 "side": "buy",
        #                 "triggerType": "fill_price",
        #                 "cTime": "1668134576563"
        #             }]
        #         }
        #     }
        #
        data = self.safe_value(response, 'data', [])
        if not isinstance(data, list):
            data = self.safe_value(data, 'orderList', [])
        return self.parse_orders(data, market, since, limit)

    async def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}):
        """
        fetches information on multiple closed orders made by the user
        see https://bitgetlimited.github.io/apidoc/en/spot/#get-order-history
        see https://bitgetlimited.github.io/apidoc/en/mix/#get-history-orders
        :param str symbol: unified market symbol of the closed orders
        :param int|None since: timestamp in ms of the earliest order
        :param int|None limit: the max number of closed orders to return
        :param dict params: extra parameters specific to the bitget api endpoint
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        await self.load_markets()
        self.check_required_symbol('fetchClosedOrders', symbol)
        market = self.market(symbol)
        response = await self.fetch_canceled_and_closed_orders(symbol, since, limit, params)
        result = []
        for i in range(0, len(response)):
            entry = response[i]
            status = self.parse_order_status(self.safe_string_2(entry, 'state', 'status'))
            if status == 'closed':
                result.append(entry)
        return self.parse_orders(result, market, since, limit)

    async def fetch_canceled_orders(self, symbol=None, since=None, limit=None, params={}):
        """
        fetches information on multiple canceled orders made by the user
        see https://bitgetlimited.github.io/apidoc/en/spot/#get-order-history
        see https://bitgetlimited.github.io/apidoc/en/mix/#get-history-orders
        :param str symbol: unified market symbol of the canceled orders
        :param int|None since: timestamp in ms of the earliest order
        :param int|None limit: the max number of canceled orders to return
        :param dict params: extra parameters specific to the bitget api endpoint
        :returns dict: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        await self.load_markets()
        self.check_required_symbol('fetchCanceledOrders', symbol)
        market = self.market(symbol)
        response = await self.fetch_canceled_and_closed_orders(symbol, since, limit, params)
        result = []
        for i in range(0, len(response)):
            entry = response[i]
            status = self.parse_order_status(self.safe_string_2(entry, 'state', 'status'))
            if status == 'canceled':
                result.append(entry)
        return self.parse_orders(result, market, since, limit)

    async def fetch_canceled_and_closed_orders(self, symbol=None, since=None, limit=None, params={}):
        await self.load_markets()
        market = self.market(symbol)
        marketType = None
        marketType, params = self.handle_market_type_and_params('fetchCanceledAndClosedOrders', market, params)
        request = {
            'symbol': market['id'],
        }
        method = self.get_supported_mapping(marketType, {
            'spot': 'privateSpotPostTradeHistory',
            'swap': 'privateMixGetOrderHistory',
        })
        stop = self.safe_value(params, 'stop')
        if stop:
            if marketType == 'spot':
                method = 'privateSpotPostPlanHistoryPlan'
            else:
                method = 'privateMixGetPlanHistoryPlan'
            params = self.omit(params, 'stop')
        if marketType == 'swap' or stop:
            if limit is None:
                limit = 100
            request['pageSize'] = limit
            if since is None:
                since = 0
            request['startTime'] = since
            request['endTime'] = self.milliseconds()
        response = await getattr(self, method)(self.extend(request, params))
        #
        # spot
        #
        #     {
        #         "code": "00000",
        #         "msg": "success",
        #         "requestTime": 1663623237813,
        #         "data": [
        #             {
        #                 "accountId": "7264631750",
        #                 "symbol": "BTCUSDT_SPBL",
        #                 "orderId": "909129926745432064",
        #                 "clientOrderId": "9e12ee3d-6a87-4e68-b1cc-094422d223a5",
        #                 "price": "30001.580000000000",
        #                 "quantity": "0.000600000000",
        #                 "orderType": "limit",
        #                 "side": "sell",
        #                 "status": "full_fill",
        #                 "fillPrice": "30001.580000000000",
        #                 "fillQuantity": "0.000600000000",
        #                 "fillTotalAmount": "18.000948000000",
        #                 "cTime": "1652479386030"
        #             },
        #             ...
        #         ]
        #     }
        #
        # swap
        #
        #     {
        #         "code": "00000",
        #         "msg": "success",
        #         "requestTime": 1663622728935,
        #         "data": {
        #             "nextFlag": False,
        #             "endId": "908510348120305664",
        #             "orderList": [
        #                 {
        #                     "symbol": "BTCUSDT_UMCBL",
        #                     "size": 0.004,
        #                     "orderId": "954568553644306433",
        #                     "clientOid": "954568553677860864",
        #                     "filledQty": 0.000,
        #                     "fee": 0E-8,
        #                     "price": 18000.00,
        #                     "state": "canceled",
        #                     "side": "open_long",
        #                     "timeInForce": "normal",
        #                     "totalProfits": 0E-8,
        #                     "posSide": "long",
        #                     "marginCoin": "USDT",
        #                     "filledAmount": 0.0000,
        #                     "orderType": "limit",
        #                     "leverage": "3",
        #                     "marginMode": "fixed",
        #                     "cTime": "1663312798899",
        #                     "uTime": "1663312809425"
        #                 },
        #                 ...
        #             ]
        #         }
        #     }
        #
        # spot plan order
        #
        #     {
        #         "code": "00000",
        #         "msg": "success",
        #         "requestTime": 1668134626684,
        #         "data": {
        #             "nextFlag": False,
        #             "endId": 974792060738441216,
        #             "orderList": [
        #                 {
        #                 "orderId": "974792060738441216",
        #                 "symbol": "TRXUSDT_SPBL",
        #                 "size": "156",
        #                 "executePrice": "0.041272",
        #                 "triggerPrice": "0.041222",
        #                 "status": "cancel",
        #                 "orderType": "limit",
        #                 "side": "buy",
        #                 "triggerType": "fill_price",
        #                 "cTime": "1668134458717"
        #                 }
        #             ]
        #         }
        #     }
        #
        # swap plan order
        #
        #     {
        #         "code":"00000",
        #         "data":[
        #             {
        #                 "orderId":"803521986049314816",
        #                 "executeOrderId":"84271931884910",
        #                 "symbol":"BTCUSDT_UMCBL",
        #                 "marginCoin":"USDT",
        #                 "size":"1",
        #                 "executePrice":"38923.1",
        #                 "triggerPrice":"45000.3",
        #                 "status":"cancel",
        #                 "orderType":"limit",
        #                 "planType":"normal_plan",
        #                 "side":"open_long",
        #                 "triggerType":"fill_price",
        #                 "presetTakeProfitPrice":"0",
        #                 "presetTakeLossPrice":"0",
        #                 "ctime":"1627300490867"
        #             }
        #         ],
        #         "msg":"success",
        #         "requestTime":1627354109502
        #     }
        #
        data = self.safe_value(response, 'data')
        return self.safe_value(data, 'orderList', data)

    async def fetch_ledger(self, code=None, since=None, limit=None, params={}):
        """
        fetch the history of changes, actions done by the user or operations that altered balance of the user
        :param str|None code: unified currency code, default is None
        :param int|None since: timestamp in ms of the earliest ledger entry, default is None
        :param int|None limit: max number of ledger entrys to return, default is None
        :param dict params: extra parameters specific to the bitget api endpoint
        :returns dict: a `ledger structure <https://docs.ccxt.com/en/latest/manual.html#ledger-structure>`
        """
        await self.load_markets()
        currency = None
        request = {}
        if code is not None:
            currency = self.currency(code)
            request['coinId'] = currency['id']
        response = await self.privateSpotPostAccountBills(self.extend(request, params))
        #
        #     {
        #       code: '00000',
        #       msg: 'success',
        #       requestTime: '1645929886887',
        #       data: [
        #         {
        #           billId: '881626974170554368',
        #           coinId: '2',
        #           coinName: 'USDT',
        #           groupType: 'transfer',
        #           bizType: 'transfer-out',
        #           quantity: '-10.00000000',
        #           balance: '73.36005300',
        #           fees: '0.00000000',
        #           cTime: '1645922171146'
        #         }
        #       ]
        #     }
        #
        data = self.safe_value(response, 'data')
        return self.parse_ledger(data, currency, since, limit)

    def parse_ledger_entry(self, item, currency=None):
        #
        #     {
        #       billId: '881626974170554368',
        #       coinId: '2',
        #       coinName: 'USDT',
        #       groupType: 'transfer',
        #       bizType: 'transfer-out',
        #       quantity: '-10.00000000',
        #       balance: '73.36005300',
        #       fees: '0.00000000',
        #       cTime: '1645922171146'
        #     }
        #
        id = self.safe_string(item, 'billId')
        currencyId = self.safe_string(item, 'coinId')
        code = self.safe_currency_code(currencyId)
        amount = self.parse_number(Precise.string_abs(self.safe_string(item, 'quantity')))
        timestamp = self.safe_integer(item, 'cTime')
        bizType = self.safe_string(item, 'bizType')
        direction = None
        if bizType is not None and bizType.find('-') >= 0:
            parts = bizType.split('-')
            direction = parts[1]
        type = self.safe_string(item, 'groupType')
        fee = self.safe_number(item, 'fees')
        after = self.safe_number(item, 'balance')
        return {
            'info': item,
            'id': id,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'direction': direction,
            'account': None,
            'referenceId': None,
            'referenceAccount': None,
            'type': type,
            'currency': code,
            'amount': amount,
            'before': None,
            'after': after,
            'status': None,
            'fee': fee,
        }

    async 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 bitget api endpoint
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>`
        """
        self.check_required_symbol('fetchMyTrades', symbol)
        await self.load_markets()
        market = self.market(symbol)
        if market['swap']:
            raise BadSymbol(self.id + ' fetchMyTrades() only supports spot markets')
        request = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = limit
        response = await self.privateSpotPostTradeFills(self.extend(request, params))
        #
        #     {
        #       code: '00000',
        #       msg: 'success',
        #       requestTime: '1645918954082',
        #       data: [
        #         {
        #           accountId: '6394957606',
        #           symbol: 'LTCUSDT_SPBL',
        #           orderId: '864752115272552448',
        #           fillId: '864752115685969921',
        #           orderType: 'limit',
        #           side: 'buy',
        #           fillPrice: '127.92000000',
        #           fillQuantity: '0.10000000',
        #           fillTotalAmount: '12.79200000',
        #           feeCcy: 'LTC',
        #           fees: '0.00000000',
        #           cTime: '1641898891373'
        #         }
        #       ]
        #     }
        #
        data = self.safe_value(response, 'data')
        return self.parse_trades(data, market, since, limit)

    async 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 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 bitget api endpoint
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>`
        """
        self.check_required_symbol('fetchOrderTrades', symbol)
        await self.load_markets()
        market = self.market(symbol)
        marketType, query = self.handle_market_type_and_params('fetchOrderTrades', market, params)
        method = self.get_supported_mapping(marketType, {
            'spot': 'privateSpotPostTradeFills',
            'swap': 'privateMixGetOrderFills',
        })
        request = {
            'symbol': market['id'],
            'orderId': id,
        }
        response = await getattr(self, method)(self.extend(request, query))
        # spot
        #
        # swap
        #     {
        #       code: '00000',
        #       msg: 'success',
        #       requestTime: 1645927862710,
        #       data: [
        #         {
        #           tradeId: '881640729552281602',
        #           symbol: 'BTCUSDT_UMCBL',
        #           orderId: '881640729145409536',
        #           price: '38429.50',
        #           sizeQty: '0.001',
        #           fee: '0',
        #           side: 'open_long',
        #           fillAmount: '38.4295',
        #           profit: '0',
        #           cTime: '1645925450694'
        #         }
        #       ]
        #     }
        #
        data = self.safe_value(response, 'data')
        return await self.parse_trades(data, market, since, limit)

    async 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 bitget api endpoint
        :returns dict: a `position structure <https://docs.ccxt.com/en/latest/manual.html#position-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
            'marginCoin': market['settleId'],
        }
        response = await self.privateMixGetPositionSinglePosition(self.extend(request, params))
        #
        #     {
        #       code: '00000',
        #       msg: 'success',
        #       requestTime: '1645933957584',
        #       data: [
        #         {
        #           marginCoin: 'USDT',
        #           symbol: 'BTCUSDT_UMCBL',
        #           holdSide: 'long',
        #           openDelegateCount: '0',
        #           margin: '1.921475',
        #           available: '0.001',
        #           locked: '0',
        #           total: '0.001',
        #           leverage: '20',
        #           achievedProfits: '0',
        #           averageOpenPrice: '38429.5',
        #           marginMode: 'fixed',
        #           holdMode: 'double_hold',
        #           unrealizedPL: '0.1634',
        #           liquidationPrice: '0',
        #           keepMarginRate: '0.004',
        #           cTime: '1645922194988'
        #         }
        #       ]
        #     }
        #
        data = self.safe_value(response, 'data', [])
        return self.parse_positions(data)

    async 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 bitget api endpoint
        :returns [dict]: a list of `position structure <https://docs.ccxt.com/en/latest/manual.html#position-structure>`
        """
        sandboxMode = self.safe_value(self.options, 'sandboxMode', False)
        await self.load_markets()
        market = None
        if symbols is not None:
            first = self.safe_string(symbols, 0)
            market = self.market(first)
        subType = None
        subType, params = self.handle_sub_type_and_params('fetchPositions', market, params)
        productType = 'UMCBL' if (subType == 'linear') else 'DMCBL'
        if sandboxMode:
            productType = 'S' + productType
        request = {
            'productType': productType,
        }
        response = await self.privateMixGetPositionAllPosition(self.extend(request, params))
        #
        #     {
        #       code: '00000',
        #       msg: 'success',
        #       requestTime: '1645933905060',
        #       data: [
        #         {
        #           marginCoin: 'USDT',
        #           symbol: 'BTCUSDT_UMCBL',
        #           holdSide: 'long',
        #           openDelegateCount: '0',
        #           margin: '1.921475',
        #           available: '0.001',
        #           locked: '0',
        #           total: '0.001',
        #           leverage: '20',
        #           achievedProfits: '0',
        #           averageOpenPrice: '38429.5',
        #           marginMode: 'fixed',
        #           holdMode: 'double_hold',
        #           unrealizedPL: '0.14869',
        #           liquidationPrice: '0',
        #           keepMarginRate: '0.004',
        #           cTime: '1645922194988'
        #         }
        #       ]
        #     }
        #
        position = self.safe_value(response, 'data', [])
        result = []
        for i in range(0, len(position)):
            result.append(self.parse_position(position[i]))
        symbols = self.market_symbols(symbols)
        return self.filter_by_array(result, 'symbol', symbols, False)

    def parse_position(self, position, market=None):
        #
        #     {
        #         marginCoin: 'USDT',
        #         symbol: 'BTCUSDT_UMCBL',
        #         holdSide: 'long',
        #         openDelegateCount: '0',
        #         margin: '1.921475',
        #         available: '0.001',
        #         locked: '0',
        #         total: '0.001',
        #         leverage: '20',
        #         achievedProfits: '0',
        #         averageOpenPrice: '38429.5',
        #         marginMode: 'fixed',
        #         holdMode: 'double_hold',
        #         unrealizedPL: '0.14869',
        #         liquidationPrice: '0',
        #         keepMarginRate: '0.004',
        #         cTime: '1645922194988'
        #     }
        #
        marketId = self.safe_string(position, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = market['symbol']
        timestamp = self.safe_integer(position, 'cTime')
        marginMode = self.safe_string(position, 'marginMode')
        collateral = None
        initialMargin = None
        unrealizedPnl = self.safe_string(position, 'unrealizedPL')
        rawCollateral = self.safe_string(position, 'margin')
        if marginMode == 'fixed':
            marginMode = 'isolated'
            collateral = Precise.string_add(rawCollateral, unrealizedPnl)
        elif marginMode == 'crossed':
            marginMode = 'cross'
            initialMargin = rawCollateral
        holdMode = self.safe_string(position, 'holdMode')
        hedged = None
        if holdMode == 'double_hold':
            hedged = True
        elif holdMode == 'single_hold':
            hedged = False
        side = self.safe_string(position, 'holdSide')
        leverage = self.safe_string(position, 'leverage')
        contractSizeNumber = self.safe_value(market, 'contractSize')
        contractSize = self.number_to_string(contractSizeNumber)
        baseAmount = self.safe_string(position, 'total')
        entryPrice = self.safe_string(position, 'averageOpenPrice')
        maintenanceMarginPercentage = self.safe_string(position, 'keepMarginRate')
        openNotional = Precise.string_mul(entryPrice, baseAmount)
        if initialMargin is None:
            initialMargin = Precise.string_div(openNotional, leverage)
        contracts = self.parse_number(Precise.string_div(baseAmount, contractSize))
        markPrice = self.safe_string(position, 'marketPrice')
        notional = Precise.string_mul(baseAmount, markPrice)
        initialMarginPercentage = Precise.string_div(initialMargin, notional)
        liquidationPrice = self.parse_number(self.omit_zero(self.safe_string(position, 'liquidationPrice')))
        calcTakerFeeRate = '0.0006'
        calcTakerFeeMult = '0.9994'
        if (liquidationPrice is None) and (marginMode == 'isolated') and Precise.string_gt(baseAmount, '0'):
            signedMargin = Precise.string_div(rawCollateral, baseAmount)
            signedMmp = maintenanceMarginPercentage
            if side == 'short':
                signedMargin = Precise.string_neg(signedMargin)
                signedMmp = Precise.string_neg(signedMmp)
            mmrMinusOne = Precise.string_sub('1', signedMmp)
            numerator = Precise.string_sub(entryPrice, signedMargin)
            if side == 'long':
                mmrMinusOne = Precise.string_mul(mmrMinusOne, calcTakerFeeMult)
            else:
                numerator = Precise.string_mul(numerator, calcTakerFeeMult)
            liquidationPrice = Precise.string_div(numerator, mmrMinusOne)
        feeToClose = Precise.string_mul(notional, calcTakerFeeRate)
        maintenanceMargin = Precise.string_add(Precise.string_mul(maintenanceMarginPercentage, notional), feeToClose)
        marginRatio = Precise.string_div(maintenanceMargin, collateral)
        percentage = Precise.string_mul(Precise.string_div(unrealizedPnl, initialMargin, 4), '100')
        return {
            'info': position,
            'id': None,
            'symbol': symbol,
            'notional': self.parse_number(notional),
            'marginMode': marginMode,
            'liquidationPrice': self.parse_number(liquidationPrice),
            'entryPrice': self.parse_number(entryPrice),
            'unrealizedPnl': self.parse_number(unrealizedPnl),
            'percentage': self.parse_number(percentage),
            'contracts': contracts,
            'contractSize': contractSizeNumber,
            'markPrice': self.parse_number(markPrice),
            'side': side,
            'hedged': hedged,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'maintenanceMargin': self.parse_number(maintenanceMargin),
            'maintenanceMarginPercentage': self.parse_number(maintenanceMarginPercentage),
            'collateral': self.parse_number(collateral),
            'initialMargin': self.parse_number(initialMargin),
            'initialMarginPercentage': self.parse_number(initialMarginPercentage),
            'leverage': self.parse_number(leverage),
            'marginRatio': self.parse_number(marginRatio),
        }

    async 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: timestamp in ms of the earliest funding rate to fetch
        :param int|None limit: the maximum amount of `funding rate structures <https://docs.ccxt.com/en/latest/manual.html?#funding-rate-history-structure>` to fetch
        :param dict params: extra parameters specific to the bitget api endpoint
        :returns [dict]: a list of `funding rate structures <https://docs.ccxt.com/en/latest/manual.html?#funding-rate-history-structure>`
        """
        self.check_required_symbol('fetchFundingRateHistory', symbol)
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
            # 'pageSize': limit,  # default 20
            # 'pageNo': 1,
            # 'nextPage': False,
        }
        if limit is not None:
            request['pageSize'] = limit
        response = await self.publicMixGetMarketHistoryFundRate(self.extend(request, params))
        #
        #     {
        #         "code": "00000",
        #         "msg": "success",
        #         "requestTime": 1652406728393,
        #         "data": [
        #             {
        #                 "symbol": "BTCUSDT",
        #                 "fundingRate": "-0.0003",
        #                 "settleTime": "1652396400000"
        #             },
        #         ]
        #     }
        #
        data = self.safe_value(response, 'data', [])
        rates = []
        for i in range(0, len(data)):
            entry = data[i]
            marketId = self.safe_string(entry, 'symbol')
            symbol = self.safe_symbol(marketId, market)
            timestamp = self.safe_integer(entry, 'settleTime')
            rates.append({
                'info': entry,
                'symbol': symbol,
                'fundingRate': self.safe_string(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)

    async 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 bitget api endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/en/latest/manual.html#funding-rate-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        if not market['swap']:
            raise BadSymbol(self.id + ' fetchFundingRate() supports swap contracts only')
        request = {
            'symbol': market['id'],
        }
        response = await self.publicMixGetMarketCurrentFundRate(self.extend(request, params))
        #
        #     {
        #         "code": "00000",
        #         "msg": "success",
        #         "requestTime": 1652401684275,
        #         "data": {
        #             "symbol": "BTCUSDT_UMCBL",
        #             "fundingRate": "-0.000182"
        #         }
        #     }
        #
        data = self.safe_value(response, 'data', {})
        return self.parse_funding_rate(data, market)

    def parse_funding_rate(self, contract, market=None):
        #
        #     {
        #         "symbol": "BTCUSDT_UMCBL",
        #         "fundingRate": "-0.000182"
        #     }
        #
        marketId = self.safe_string(contract, 'symbol')
        symbol = self.safe_symbol(marketId, market)
        return {
            'info': contract,
            'symbol': symbol,
            'markPrice': None,
            'indexPrice': None,
            'interestRate': None,
            'estimatedSettlePrice': None,
            'timestamp': None,
            'datetime': None,
            'fundingRate': self.safe_number(contract, 'fundingRate'),
            'fundingTimestamp': None,
            'fundingDatetime': None,
            'nextFundingRate': None,
            'nextFundingTimestamp': None,
            'nextFundingDatetime': None,
            'previousFundingRate': None,
            'previousFundingTimestamp': None,
            'previousFundingDatetime': None,
        }

    async def fetch_funding_history(self, symbol, since=None, limit=None, params={}):
        """
        fetch the funding history
        see https://bitgetlimited.github.io/apidoc/en/mix/#get-account-bill
        :param str symbol: unified market symbol
        :param int|None since: the starting timestamp in milliseconds
        :param int|None limit: the number of entries to return
        :param dict params: extra parameters specific to the bitget api endpoint
        :returns [dict]: a list of `funding history structures <https://docs.ccxt.com/en/latest/manual.html#funding-history-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        if not market['swap']:
            raise BadSymbol(self.id + ' fetchFundingHistory() supports swap contracts only')
        if since is None:
            since = self.milliseconds() - 31556952000  # 1 year
        request = {
            'symbol': market['id'],
            'marginCoin': market['quoteId'],
            'startTime': since,
            'endTime': self.milliseconds(),
        }
        if limit is not None:
            request['pageSize'] = limit
        response = await self.privateMixGetAccountAccountBill(self.extend(request, params))
        #
        #    {
        #        "code": "00000",
        #        "msg": "success",
        #        "data": {
        #            "result": [
        #                {
        #                    "id": "892962903462432768",
        #                    "symbol": "ETHUSDT_UMCBL",
        #                    "marginCoin": "USDT",
        #                    "amount": "0",
        #                    "fee": "-0.1765104",
        #                    "feeByCoupon": "",
        #                    "feeCoin": "USDT",
        #                    "business": "contract_settle_fee",
        #                    "cTime": "1648624867354"
        #                }
        #            ],
        #            "endId": "885353495773458432",
        #            "nextFlag": False,
        #            "preFlag": False
        #    }
        #
        data = self.safe_value(response, 'data', {})
        result = self.safe_value(data, 'result', [])
        return self.parse_funding_histories(result, market, since, limit)

    def parse_funding_history(self, contract, market=None):
        #
        #     {
        #         "id": "892962903462432768",
        #         "symbol": "ETHUSDT_UMCBL",
        #         "marginCoin": "USDT",
        #         "amount": "0",
        #         "fee": "-0.1765104",
        #         "feeByCoupon": "",
        #         "feeCoin": "USDT",
        #         "business": "contract_settle_fee",
        #         "cTime": "1648624867354"
        #     }
        #
        marketId = self.safe_string(contract, 'symbol')
        symbol = self.safe_symbol(marketId, market, None, 'swap')
        currencyId = self.safe_string(contract, 'marginCoin')
        code = self.safe_currency_code(currencyId)
        amount = self.safe_number(contract, 'amount')
        timestamp = self.safe_integer(contract, 'cTime')
        id = self.safe_string(contract, 'id')
        return {
            'info': contract,
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'code': code,
            'amount': amount,
            'id': id,
        }

    def parse_funding_histories(self, contracts, market=None, since=None, limit=None):
        result = []
        for i in range(0, len(contracts)):
            contract = contracts[i]
            business = self.safe_string(contract, 'business')
            if business != 'contract_settle_fee':
                continue
            result.append(self.parse_funding_history(contract, market))
        sorted = self.sort_by(result, 'timestamp')
        return self.filter_by_since_limit(sorted, since, limit)

    async def modify_margin_helper(self, symbol, amount, type, params={}):
        await self.load_markets()
        holdSide = self.safe_string(params, 'holdSide')
        market = self.market(symbol)
        marginCoin = market['quote'] if (market['linear']) else market['base']
        request = {
            'symbol': market['id'],
            'marginCoin': marginCoin,
            'amount': self.amount_to_precision(symbol, amount),  # positive value for adding margin, negative for reducing
            'holdSide': holdSide,  # long or short
        }
        params = self.omit(params, 'holdSide')
        response = await self.privateMixPostAccountSetMargin(self.extend(request, params))
        #
        #     {
        #         "code": "00000",
        #         "msg": "success",
        #         "requestTime": 1652483636792,
        #         "data": {
        #             "result": True
        #         }
        #     }
        #
        return self.extend(self.parse_margin_modification(response, market), {
            'amount': self.parse_number(amount),
            'type': type,
        })

    def parse_margin_modification(self, data, market=None):
        errorCode = self.safe_string(data, 'code')
        status = 'ok' if (errorCode == '00000') else 'failed'
        code = market['quote'] if (market['linear']) else market['base']
        return {
            'info': data,
            'type': None,
            'amount': None,
            'code': code,
            'symbol': market['symbol'],
            'status': status,
        }

    async 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 bitget api endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/en/latest/manual.html#reduce-margin-structure>`
        """
        if amount > 0:
            raise BadRequest(self.id + ' reduceMargin() amount parameter must be a negative value')
        holdSide = self.safe_string(params, 'holdSide')
        if holdSide is None:
            raise ArgumentsRequired(self.id + ' reduceMargin() requires a holdSide parameter, either long or short')
        return await self.modify_margin_helper(symbol, amount, 'reduce', params)

    async 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 bitget api endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/en/latest/manual.html#add-margin-structure>`
        """
        holdSide = self.safe_string(params, 'holdSide')
        if holdSide is None:
            raise ArgumentsRequired(self.id + ' addMargin() requires a holdSide parameter, either long or short')
        return await self.modify_margin_helper(symbol, amount, 'add', params)

    async def fetch_leverage(self, symbol, params={}):
        """
        fetch the set leverage for a market
        :param str symbol: unified market symbol
        :param dict params: extra parameters specific to the bitget api endpoint
        :returns dict: a `leverage structure <https://docs.ccxt.com/en/latest/manual.html#leverage-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
            'marginCoin': market['settleId'],
        }
        response = await self.privateMixGetAccountAccount(self.extend(request, params))
        #
        #     {
        #         "code": "00000",
        #         "msg": "success",
        #         "requestTime": 0,
        #         "data": {
        #             "marginCoin": "SUSDT",
        #             "locked": "0",
        #             "available": "3000",
        #             "crossMaxAvailable": "3000",
        #             "fixedMaxAvailable": "3000",
        #             "maxTransferOut": "3000",
        #             "equity": "3000",
        #             "usdtEquity": "3000",
        #             "btcEquity": "0.12217217236",
        #             "crossRiskRate": "0",
        #             "crossMarginLeverage": 20,
        #             "fixedLongLeverage": 40,
        #             "fixedShortLeverage": 10,
        #             "marginMode": "fixed",
        #             "holdMode": "double_hold",
        #             "unrealizedPL": null,
        #             "bonus": "0"
        #         }
        #     }
        #
        return response

    async 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 symbol: unified market symbol
        :param dict params: extra parameters specific to the bitget api endpoint
        :returns dict: response from the exchange
        """
        self.check_required_symbol('setLeverage', symbol)
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
            'marginCoin': market['settleId'],
            'leverage': leverage,
            # 'holdSide': 'long',
        }
        return await self.privateMixPostAccountSetLeverage(self.extend(request, params))

    async def set_margin_mode(self, marginMode, symbol=None, params={}):
        """
        set margin mode to 'cross' or 'isolated'
        :param str marginMode: 'cross' or 'isolated'
        :param str symbol: unified market symbol
        :param dict params: extra parameters specific to the bitget api endpoint
        :returns dict: response from the exchange
        """
        self.check_required_symbol('setMarginMode', symbol)
        marginMode = marginMode.lower()
        if (marginMode != 'fixed') and (marginMode != 'crossed'):
            raise ArgumentsRequired(self.id + ' setMarginMode() marginMode must be "fixed" or "crossed"')
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
            'marginCoin': market['settleId'],
            'marginMode': marginMode,
        }
        return await self.privateMixPostAccountSetMarginMode(self.extend(request, params))

    async def set_position_mode(self, hedged, symbol=None, params={}):
        """
        set hedged to True or False for a market
        :param bool hedged: set to True to use dualSidePosition
        :param str|None symbol: not used by bitget setPositionMode()
        :param dict params: extra parameters specific to the bitget api endpoint
        :returns dict: response from the exchange
         *
        """
        await self.load_markets()
        sandboxMode = self.safe_value(self.options, 'sandboxMode', False)
        holdMode = 'double_hold' if hedged else 'single_hold'
        request = {
            'holdMode': holdMode,
        }
        subType = None
        market = None
        if symbol is not None:
            market = self.market(symbol)
        subType, params = self.handle_sub_type_and_params('setPositionMode', market, params)
        productType = 'UMCBL' if (subType == 'linear') else 'DMCBL'
        if sandboxMode:
            productType = 'S' + productType
        request['productType'] = productType
        response = await self.privateMixPostAccountSetPositionMode(self.extend(request, params))
        #
        #    {
        #         "code": "40919",
        #         "msg": "This function is not open yet",
        #         "requestTime": 1672212431093,
        #         "data": null
        #     }
        #
        return response

    async def fetch_open_interest(self, symbol, params={}):
        """
        Retrieves the open interest of a currency
        see https://bitgetlimited.github.io/apidoc/en/mix/#get-open-interest
        :param str symbol: Unified CCXT market symbol
        :param dict params: exchange specific parameters
        :returns dict} an open interest structure{@link https://docs.ccxt.com/en/latest/manual.html#interest-history-structure:
        """
        await self.load_markets()
        market = self.market(symbol)
        if not market['contract']:
            raise BadRequest(self.id + ' fetchOpenInterest() supports contract markets only')
        request = {
            'symbol': market['id'],
        }
        response = await self.publicMixGetMarketOpenInterest(self.extend(request, params))
        #
        #     {
        #         "code": "00000",
        #         "msg": "success",
        #         "requestTime": 0,
        #         "data": {
        #             "symbol": "BTCUSDT_UMCBL",
        #             "amount": "130818.967",
        #             "timestamp": "1663399151127"
        #         }
        #     }
        #
        data = self.safe_value(response, 'data', {})
        return self.parse_open_interest(data, market)

    async def fetch_transfers(self, code=None, since=None, limit=None, params={}):
        """
        fetch a history of internal transfers made on an account
        see https://bitgetlimited.github.io/apidoc/en/spot/#get-transfer-list
        :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 bitget api endpoint
        :returns [dict]: a list of `transfer structures <https://docs.ccxt.com/en/latest/manual.html#transfer-structure>`
        """
        await self.load_markets()
        type = None
        type, params = self.handle_market_type_and_params('fetchTransfers', None, params)
        fromAccount = self.safe_string(params, 'fromAccount', type)
        params = self.omit(params, 'fromAccount')
        accountsByType = self.safe_value(self.options, 'accountsByType', {})
        type = self.safe_string(accountsByType, fromAccount)
        request = {
            'fromType': type,
        }
        currency = None
        if code is not None:
            currency = self.currency(code)
            request['coinId'] = currency['id']
        if since is not None:
            request['before'] = since
        if limit is not None:
            request['limit'] = limit
        response = await self.privateSpotGetAccountTransferRecords(self.extend(request, params))
        #
        #     {
        #         "code":"00000",
        #         "message":"success",
        #         "data":[{
        #             "cTime":"1622697148",
        #             "coinId":"22",
        #             "coinName":"usdt",
        #             "groupType":"deposit",
        #             "bizType":"transfer-in",
        #             "quantity":"1",
        #             "balance": "1",
        #             "fees":"0",
        #             "billId":"1291"
        #         }]
        #     }
        #
        data = self.safe_value(response, 'data', [])
        return self.parse_transfers(data, currency, since, limit)

    async def transfer(self, code, amount, fromAccount, toAccount, params={}):
        """
        see https://bitgetlimited.github.io/apidoc/en/spot/#transfer
        transfer currency internally between wallets on the same account
        :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 bitget api endpoint
         *
         * EXCHANGE SPECIFIC PARAMS
        :param str params['clientOid']: custom id
        :returns dict: a `transfer structure <https://docs.ccxt.com/en/latest/manual.html#transfer-structure>`
        """
        await self.load_markets()
        currency = self.currency(code)
        fromSwap = fromAccount == 'swap'
        toSwap = toAccount == 'swap'
        usdt = currency['code'] == 'USDT'
        if fromSwap:
            fromAccount = 'mix_usdt' if usdt else 'mix_usd'
        elif toSwap:
            toAccount = 'mix_usdt' if usdt else 'mix_usd'
        request = {
            'fromType': fromAccount,
            'toType': toAccount,
            'amount': amount,
            'coin': currency['info']['coinName'],
        }
        response = await self.privateSpotPostWalletTransfer(self.extend(request, params))
        #
        #    {
        #        "code": "00000",
        #        "msg": "success",
        #        "requestTime": 1668119107154,
        #        "data": "SUCCESS"
        #    }
        #
        return self.parse_transfer(response, currency)

    def parse_transfer(self, transfer, currency=None):
        #
        # transfer
        #
        #    {
        #        "code": "00000",
        #        "msg": "success",
        #        "requestTime": 1668119107154,
        #        "data": "SUCCESS"
        #    }
        #
        # fetchTransfers
        #
        #     {
        #         "cTime":"1622697148",
        #         "coinId":"22",
        #         "coinName":"usdt",
        #         "groupType":"deposit",
        #         "bizType":"transfer-in",
        #         "quantity":"1",
        #         "balance": "1",
        #         "fees":"0",
        #         "billId":"1291"
        #     }
        #
        timestamp = self.safe_integer_2(transfer, 'requestTime', 'tradeTime')
        if timestamp is None:
            timestamp = self.safe_timestamp(transfer, 'cTime')
        msg = self.safe_string_lower_n(transfer, ['msg', 'status'])
        currencyId = self.safe_string_2(transfer, 'code', 'coinName')
        if currencyId == '00000':
            currencyId = None
        fromAccountRaw = self.safe_string(transfer, 'fromType')
        accountsById = self.safe_value(self.options, 'accountsById', {})
        fromAccount = self.safe_string(accountsById, fromAccountRaw, fromAccountRaw)
        toAccountRaw = self.safe_string(transfer, 'toType')
        toAccount = self.safe_string(accountsById, toAccountRaw, toAccountRaw)
        return {
            'info': transfer,
            'id': self.safe_string_2(transfer, 'id', 'billId'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'currency': self.safe_currency_code(currencyId),
            'amount': self.safe_number_n(transfer, ['size', 'quantity', 'amount']),
            'fromAccount': fromAccount,
            'toAccount': toAccount,
            'status': self.parse_transfer_status(msg),
        }

    def parse_transfer_status(self, status):
        statuses = {
            'success': 'ok',
            'successful': 'ok',
        }
        return self.safe_string(statuses, status, status)

    def parse_open_interest(self, interest, market=None):
        #
        #     {
        #         "symbol": "BTCUSDT_UMCBL",
        #         "amount": "130818.967",
        #         "timestamp": "1663399151127"
        #     }
        #
        timestamp = self.safe_integer(interest, 'timestamp')
        id = self.safe_string(interest, 'symbol')
        symbol = self.safe_symbol(id, market)
        amount = self.safe_number(interest, 'amount')
        return {
            'symbol': symbol,
            'openInterestAmount': amount,
            'openInterestValue': None,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'info': interest,
        }

    def handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody):
        if not response:
            return  # fallback to default error handler
        #
        # spot
        #
        #     {"status":"fail","err_code":"01001","err_msg":"系统异常，请稍后重试"}
        #     {"status":"error","ts":1595594160149,"err_code":"invalid-parameter","err_msg":"invalid size, valid range: [1,2000]"}
        #     {"status":"error","ts":1595684716042,"err_code":"invalid-parameter","err_msg":"illegal sign invalid"}
        #     {"status":"error","ts":1595700216275,"err_code":"bad-request","err_msg":"your balance is low!"}
        #     {"status":"error","ts":1595700344504,"err_code":"invalid-parameter","err_msg":"invalid type"}
        #     {"status":"error","ts":1595703343035,"err_code":"bad-request","err_msg":"order cancel fail"}
        #     {"status":"error","ts":1595704360508,"err_code":"invalid-parameter","err_msg":"accesskey not null"}
        #     {"status":"error","ts":1595704490084,"err_code":"invalid-parameter","err_msg":"permissions not right"}
        #     {"status":"error","ts":1595711862763,"err_code":"system exception","err_msg":"system exception"}
        #     {"status":"error","ts":1595730308979,"err_code":"bad-request","err_msg":"20003"}
        #
        # swap
        #
        #     {"code":"40015","msg":"","requestTime":1595698564931,"data":null}
        #     {"code":"40017","msg":"Order id must not be blank","requestTime":1595702477835,"data":null}
        #     {"code":"40017","msg":"Order Type must not be blank","requestTime":1595698516162,"data":null}
        #     {"code":"40301","msg":"","requestTime":1595667662503,"data":null}
        #     {"code":"40017","msg":"Contract code must not be blank","requestTime":1595703151651,"data":null}
        #     {"code":"40108","msg":"","requestTime":1595885064600,"data":null}
        #     {"order_id":"513468410013679613","client_oid":null,"symbol":"ethusd","result":false,"err_code":"order_no_exist_error","err_msg":"订单不存在！"}
        #
        message = self.safe_string(response, 'err_msg')
        errorCode = self.safe_string_2(response, 'code', 'err_code')
        feedback = self.id + ' ' + body
        nonEmptyMessage = ((message is not None) and (message != ''))
        if nonEmptyMessage:
            self.throw_exactly_matched_exception(self.exceptions['exact'], message, feedback)
            self.throw_broadly_matched_exception(self.exceptions['broad'], message, feedback)
        nonZeroErrorCode = (errorCode is not None) and (errorCode != '00000')
        if nonZeroErrorCode:
            self.throw_exactly_matched_exception(self.exceptions['exact'], errorCode, feedback)
        if nonZeroErrorCode or nonEmptyMessage:
            raise ExchangeError(feedback)  # unknown message

    def sign(self, path, api=[], method='GET', params={}, headers=None, body=None):
        signed = api[0] == 'private'
        endpoint = api[1]
        pathPart = '/api/spot/v1' if (endpoint == 'spot') else '/api/mix/v1'
        request = '/' + self.implode_params(path, params)
        payload = pathPart + request
        url = self.implode_hostname(self.urls['api'][endpoint]) + payload
        query = self.omit(params, self.extract_params(path))
        if not signed and (method == 'GET'):
            keys = list(query.keys())
            keysLength = len(keys)
            if keysLength > 0:
                url = url + '?' + self.urlencode(query)
        if signed:
            self.check_required_credentials()
            timestamp = str(self.milliseconds())
            auth = timestamp + method + payload
            if method == 'POST':
                body = self.json(params)
                auth += body
            else:
                if params:
                    query = '?' + self.urlencode(self.keysort(params))
                    url += query
                    auth += query
            signature = self.hmac(self.encode(auth), self.encode(self.secret), hashlib.sha256, 'base64')
            broker = self.safe_string(self.options, 'broker')
            headers = {
                'ACCESS-KEY': self.apiKey,
                'ACCESS-SIGN': signature,
                'ACCESS-TIMESTAMP': timestamp,
                'ACCESS-PASSPHRASE': self.password,
                'X-CHANNEL-API-CODE': broker,
            }
            if method == 'POST':
                headers['Content-Type'] = 'application/json'
        return {'url': url, 'method': method, 'body': body, 'headers': headers}
