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

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

from ccxt.base.exchange import Exchange
from ccxt.abstract.backpack import ImplicitAPI
from ccxt.base.types import Any, Balances, Bool, Currencies, Currency, DepositAddress, Int, Market, MarketType, Num, Order, OrderBook, OrderRequest, OrderSide, OrderType, Position, Str, Strings, Ticker, Tickers, FundingRate, Trade, Transaction
from typing import List
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
from ccxt.base.errors import BadSymbol
from ccxt.base.errors import OperationRejected
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OperationFailed
from ccxt.base.errors import NetworkError
from ccxt.base.errors import RateLimitExceeded
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.errors import RequestTimeout
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise


class backpack(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(backpack, self).describe(), {
            'id': 'backpack',
            'name': 'Backpack',
            'countries': ['JP'],  # Japan
            'rateLimit': 50,  # 20 times per second
            'version': 'v1',
            'certified': False,
            'pro': True,
            'has': {
                'CORS': None,
                'spot': True,
                'margin': True,
                'swap': True,
                'future': False,
                'option': False,
                'addMargin': False,
                'cancelAllOrders': True,
                'cancelAllOrdersAfter': False,
                'cancelOrder': True,
                'cancelOrders': False,
                'cancelWithdraw': False,
                'closePosition': False,
                'createConvertTrade': False,  # todo
                'createDepositAddress': False,
                'createLimitBuyOrder': True,
                'createLimitOrder': True,
                'createLimitSellOrder': True,
                'createMarketBuyOrder': True,
                'createMarketBuyOrderWithCost': True,
                'createMarketOrder': True,
                'createMarketOrderWithCost': True,
                'createMarketSellOrder': True,
                'createMarketSellOrderWithCost': True,
                'createOrder': True,
                'createOrders': True,
                'createOrderWithTakeProfitAndStopLoss': True,
                'createPostOnlyOrder': True,
                'createReduceOnlyOrder': True,
                'createStopLossOrder': False,
                'createTakeProfitOrder': False,
                'createTrailingAmountOrder': False,
                'createTrailingPercentOrder': False,
                'createTriggerOrder': True,
                'fetchAccounts': False,
                'fetchAllGreeks': False,
                'fetchBalance': True,
                'fetchCanceledAndClosedOrders': False,
                'fetchCanceledOrders': False,
                'fetchClosedOrder': False,
                'fetchClosedOrders': False,
                'fetchConvertCurrencies': False,
                'fetchConvertQuote': False,
                'fetchConvertTrade': False,
                'fetchConvertTradeHistory': False,
                'fetchCurrencies': True,
                'fetchDepositAddress': True,
                'fetchDeposits': True,
                'fetchDepositsWithdrawals': False,
                'fetchDepositWithdrawFees': False,
                'fetchFundingHistory': True,
                'fetchFundingRate': True,
                'fetchFundingRateHistory': True,
                'fetchFundingRates': False,
                'fetchGreeks': False,
                'fetchIndexOHLCV': True,
                'fetchLedger': False,
                'fetchLeverage': False,
                'fetchLeverageTiers': False,
                'fetchMarginAdjustmentHistory': False,
                'fetchMarginMode': False,
                'fetchMarkets': True,
                'fetchMarkOHLCV': True,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenInterest': True,
                'fetchOpenInterestHistory': True,
                'fetchOpenOrder': True,
                'fetchOpenOrders': True,
                'fetchOption': False,
                'fetchOptionChain': False,
                'fetchOrder': False,
                'fetchOrderBook': True,
                'fetchOrders': True,
                'fetchOrderTrades': False,
                'fetchPosition': False,
                'fetchPositionHistory': False,
                'fetchPositionMode': False,
                'fetchPositions': True,
                'fetchPositionsForSymbol': False,
                'fetchPositionsHistory': False,
                'fetchPremiumIndexOHLCV': False,
                'fetchStatus': True,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTime': True,
                'fetchTrades': True,
                'fetchTradingFee': False,
                'fetchTradingFees': False,
                'fetchTransactions': False,
                'fetchTransfers': False,
                'fetchVolatilityHistory': False,
                'fetchWithdrawals': True,
                'reduceMargin': False,
                'sandbox': False,
                'setLeverage': False,
                'setMargin': False,
                'setMarginMode': False,
                'setPositionMode': False,
                'transfer': False,
                'withdraw': True,
            },
            'timeframes': {
                '1m': '1m',
                '3m': '3m',
                '5m': '5m',
                '15': '15m',
                '30': '30m',
                '1h': '1h',
                '2h': '2h',
                '4h': '4h',
                '6h': '6h',
                '8h': '8h',
                '12h': '12h',
                '1d': '1d',
                '3d': '3d',
                '1w': '1w',
                '1M': '1month',
            },
            'urls': {
                'logo': 'https://github.com/user-attachments/assets/cc04c278-679f-4554-9f72-930dd632b80f',
                'api': {
                    'public': 'https://api.backpack.exchange',
                    'private': 'https://api.backpack.exchange',
                },
                'www': 'https://backpack.exchange/',
                'doc': 'https://docs.backpack.exchange/',
                'referral': 'https://backpack.exchange/join/ccxt',
            },
            'api': {
                'public': {
                    'get': {
                        'api/v1/assets': 1,  # done
                        'api/v1/collateral': 1,  # not used
                        'api/v1/borrowLend/markets': 1,
                        'api/v1/borrowLend/markets/history': 1,
                        'api/v1/markets': 1,  # done
                        'api/v1/market': 1,  # not used
                        'api/v1/ticker': 1,  # done
                        'api/v1/tickers': 1,  # done
                        'api/v1/depth': 1,  # done
                        'api/v1/klines': 1,  # done
                        'api/v1/markPrices': 1,  # done
                        'api/v1/openInterest': 1,  # done
                        'api/v1/fundingRates': 1,  # done
                        'api/v1/status': 1,  # done
                        'api/v1/ping': 1,  # todo check if it is needed for ws
                        'api/v1/time': 1,  # done
                        'api/v1/wallets': 1,  # not used
                        'api/v1/trades': 1,  # done
                        'api/v1/trades/history': 1,  # done
                    },
                },
                'private': {
                    'get': {
                        'api/v1/account': 1,  # todo fetchTradingFee
                        'api/v1/account/limits/borrow': 1,  # not used
                        'api/v1/account/limits/order': 1,  # not used
                        'api/v1/account/limits/withdrawal': 1,  # not used
                        'api/v1/borrowLend/positions': 1,  # todo fetchBorrowInterest
                        'api/v1/capital': 1,  # done
                        'api/v1/capital/collateral': 1,  # not used
                        'wapi/v1/capital/deposits': 1,  # done
                        'wapi/v1/capital/deposit/address': 1,  # done
                        'wapi/v1/capital/withdrawals': 1,  # todo complete after withdrawal
                        'api/v1/position': 1,  # done but todo check if all is right
                        'wapi/v1/history/borrowLend': 1,  # not used
                        'wapi/v1/history/interest': 1,  # not used
                        'wapi/v1/history/borrowLend/positions': 1,  # not used
                        'wapi/v1/history/dust': 1,  # not used
                        'wapi/v1/history/fills': 1,  # done
                        'wapi/v1/history/funding': 1,  # done
                        'wapi/v1/history/orders': 1,  # done
                        'wapi/v1/history/rfq': 1,
                        'wapi/v1/history/quote': 1,
                        'wapi/v1/history/settlement': 1,
                        'wapi/v1/history/strategies': 1,
                        'api/v1/order': 1,  # done
                        'api/v1/orders': 1,  # done
                    },
                    'post': {
                        'api/v1/account/convertDust': 1,
                        'api/v1/borrowLend': 1,  # todo borrowCrossMargin
                        'wapi/v1/capital/withdrawals': 1,  # todo complete after withdrawal
                        'api/v1/order': 1,  # done
                        'api/v1/orders': 1,  # done
                        'api/v1/rfq': 1,
                        'api/v1/rfq/accept': 1,
                        'api/v1/rfq/refresh': 1,
                        'api/v1/rfq/cancel': 1,
                        'api/v1/rfq/quote': 1,
                    },
                    'delete': {
                        'api/v1/order': 1,  # done
                        'api/v1/orders': 1,  # done
                    },
                    'patch': {
                        'api/v1/account': 1,
                    },
                },
            },
            'features': {
                'default': {
                    'sandbox': False,
                    'createOrder': {
                        'marginMode': False,
                        'triggerPrice': True,
                        'triggerPriceType': None,
                        'triggerDirection': False,
                        'stopLossPrice': True,
                        'takeProfitPrice': True,
                        'attachedStopLossTakeProfit': None,
                        'timeInForce': {
                            'GTC': True,
                            'IOC': True,
                            'FOK': True,
                            'PO': True,
                            'GTD': False,
                        },
                        'hedged': False,
                        'trailing': False,
                        'leverage': False,
                        'marketBuyByCost': True,
                        'marketBuyRequiresPrice': True,
                        'selfTradePrevention': {
                            'EXPIRE_MAKER': True,
                            'EXPIRE_TAKER': True,
                            'EXPIRE_BOTH': True,
                            'NONE': False,
                        },
                        'iceberg': False,
                    },
                    'createOrders': {
                        'max': 20,
                    },
                    'fetchMyTrades': {
                        'marginMode': False,
                        'limit': 1000,
                        'daysBack': None,
                        'untilDays': None,
                        'symbolRequired': False,
                    },
                    'fetchOrder': None,
                    'fetchOpenOrders': {
                        'marginMode': False,
                        'limit': 1000,
                        'trigger': True,
                        'trailing': False,
                        'symbolRequired': False,
                    },
                    'fetchOrders': {
                        'marginMode': False,
                        'limit': 1000,
                        'daysBack': None,
                        'untilDays': None,
                        'trigger': True,
                        'trailing': False,
                        'symbolRequired': True,
                    },
                    'fetchClosedOrders': None,
                    'fetchOHLCV': {
                        'paginate': False,
                        'limit': 1000,
                    },
                },
                'spot': {
                    'extends': 'default',
                },
                'swap': {
                    'linear': None,
                    'inverse': None,
                },
                'future': {
                    'linear': None,
                    'inverse': None,
                },
            },
            'requiredCredentials': {
                'apiKey': True,
                'secret': True,
            },
            'precisionMode': TICK_SIZE,
            'options': {
                'instructions': {
                    'api/v1/account': {
                        'GET': 'accountQuery',
                        'PATCH': 'accountUpdate',
                    },
                    'api/v1/capital': {
                        'GET': 'balanceQuery',
                    },
                    'api/v1/account/limits/borrow': {
                        'GET': 'maxBorrowQuantity',
                    },
                    'api/v1/account/limits/order': {
                        'GET': 'maxOrderQuantity',
                    },
                    'api/v1/account/limits/withdrawal': {
                        'GET': 'maxWithdrawalQuantity',
                    },
                    'api/v1/borrowLend/positions': {
                        'GET': 'borrowLendPositionQuery',
                    },
                    'api/v1/borrowLend': {
                        'POST': 'borrowLendExecute',
                    },
                    'wapi/v1/history/borrowLend/positions': {
                        'GET': 'borrowPositionHistoryQueryAll',
                    },
                    'wapi/v1/history/borrowLend': {
                        'GET': 'borrowHistoryQueryAll',
                    },
                    'wapi/v1/history/dust': {
                        'GET': 'dustHistoryQueryAll',
                    },
                    'api/v1/capital/collateral': {
                        'GET': 'collateralQuery',
                    },
                    'wapi/v1/capital/deposit/address': {
                        'GET': 'depositAddressQuery',
                    },
                    'wapi/v1/capital/deposits': {
                        'GET': 'depositQueryAll',
                    },
                    'wapi/v1/history/fills': {
                        'GET': 'fillHistoryQueryAll',
                    },
                    'wapi/v1/history/funding': {
                        'GET': 'fundingHistoryQueryAll',
                    },
                    'wapi/v1/history/interest': {
                        'GET': 'interestHistoryQueryAll',
                    },
                    'api/v1/order': {
                        'GET': 'orderQuery',
                        'POST': 'orderExecute',
                        'DELETE': 'orderCancel',
                    },
                    'api/v1/orders': {
                        'GET': 'orderQueryAll',
                        'POST': 'orderExecute',
                        'DELETE': 'orderCancelAll',
                    },
                    'wapi/v1/history/orders': {
                        'GET': 'orderHistoryQueryAll',
                    },
                    'wapi/v1/history/pnl': {
                        'GET': 'pnlHistoryQueryAll',
                    },
                    'wapi/v1/history/rfq': {
                        'GET': 'rfqHistoryQueryAll',
                    },
                    'wapi/v1/history/quote': {
                        'GET': 'quoteHistoryQueryAll',
                    },
                    'wapi/v1/history/settlement': {
                        'GET': 'settlementHistoryQueryAll',
                    },
                    'api/v1/position': {
                        'GET': 'positionQuery',
                    },
                    'api/v1/rfq/quote': {
                        'POST': 'quoteSubmit',
                    },
                    'wapi/v1/history/strategies': {
                        'GET': 'strategyHistoryQueryAll',
                    },
                    'wapi/v1/capital/withdrawals': {
                        'GET': 'withdrawalQueryAll',
                        'POST': 'withdraw',
                    },
                },
                'recvWindow': 5000,  # default is 5000, max is 60000
                'brokerId': '',
                'currencyIdsListForParseMarket': None,
                'broker': '',
                'timeDifference': 0,  # the difference between system clock and the exchange server clock in milliseconds
                'adjustForTimeDifference': False,  # controls the adjustment logic upon instantiation
                'networks': {
                    'APT': 'Aptos',
                    'ARB': 'Arbitrum',
                    'AVAX': 'Avalanche',
                    'BASE': 'Base',
                    'BERA': 'Berachain',
                    'BTC': 'Bitcoin',
                    'BCH': 'BitcoinCash',
                    'BSC': 'Bsc',
                    'ADA': 'Cardano',
                    'DOGE': 'Dogecoin',
                    'ECLIPSE': 'Eclipse',
                    'EQUALSMONEY': 'EqualsMoney',
                    'ERC20': 'Ethereum',
                    'HYP': 'Hyperliquid',
                    'LTC': 'Litecoin',
                    'OPTIMISM': 'Optimism',
                    'MATIC': 'Polygon',
                    'SEI': 'Sei',
                    'SUI': 'Sui',
                    'SOL': 'Solana',
                    'STORY': 'Story',
                    'TRC20': 'Tron',
                    'XRP': 'XRP',
                },
                'networksById': {
                    'aptos': 'APT',
                    'arbitrum': 'ARB',
                    'avalanche': 'AVAX',
                    'base': 'BASE',
                    'berachain': 'BERA',
                    'bitcoin': 'BTC',
                    'bitcoincash': 'BCH',
                    'bsc': 'BSC',
                    'cardano': 'ADA',
                    'dogecoin': 'DOGE',
                    'eclipse': 'ECLIPSE',
                    'equalsmoney': 'EQUALSMONEY',
                    'ethereum': 'ERC20',
                    'hyperliquid': 'HYP',
                    'litecoin': 'LTC',
                    'optimism': 'OPTIMISM',
                    'polygon': 'MATIC',
                    'sei': 'SEI',
                    'sui': 'SUI',
                    'solana': 'SOL',
                    'story': 'STORY',
                    'tron': 'TRC20',
                    'xrp': 'XRP',
                },
            },
            'commonCurrencies': {},
            'exceptions': {
                'exact': {
                    'INVALID_CLIENT_REQUEST': BadRequest,
                    'INVALID_ORDER': InvalidOrder,
                    'ACCOUNT_LIQUIDATING': BadRequest,
                    'BORROW_LIMIT': BadRequest,
                    'BORROW_REQUIRES_LEND_REDEEM': BadRequest,
                    'FORBIDDEN': OperationRejected,
                    'INSUFFICIENT_FUNDS': InsufficientFunds,
                    'INSUFFICIENT_MARGIN': InsufficientFunds,
                    'INSUFFICIENT_SUPPLY': InsufficientFunds,
                    'INVALID_ASSET': BadRequest,
                    'INVALID_MARKET': BadSymbol,
                    'INVALID_PRICE': BadRequest,
                    'INVALID_POSITION_ID': BadRequest,
                    'INVALID_QUANTITY': BadRequest,
                    'INVALID_RANGE': BadRequest,
                    'INVALID_SIGNATURE': AuthenticationError,
                    'INVALID_SOURCE': BadRequest,
                    'INVALID_SYMBOL': BadSymbol,
                    'INVALID_TWO_FACTOR_CODE': BadRequest,
                    'LEND_LIMIT': BadRequest,
                    'LEND_REQUIRES_BORROW_REPAY': BadRequest,
                    'MAINTENANCE': ExchangeError,
                    'MAX_LEVERAGE_REACHED': InsufficientFunds,
                    'NOT_IMPLEMENTED': OperationFailed,
                    'ORDER_LIMIT': OperationRejected,
                    'POSITION_LIMIT': OperationRejected,
                    'PRECONDITION_FAILED': OperationFailed,
                    'RESOURCE_NOT_FOUND': ExchangeNotAvailable,
                    'SERVER_ERROR': NetworkError,
                    'TIMEOUT': RequestTimeout,
                    'TOO_MANY_REQUESTS': RateLimitExceeded,
                    'TRADING_PAUSED': ExchangeNotAvailable,
                    'UNAUTHORIZED': AuthenticationError,
                },
                # Bad Request parse request payload error: failed to parse "MarketSymbol": Invalid market symbol(occurred while parsing "OrderExecutePayload")
                # failed to parse parameter `interval`: failed to parse "KlineInterval": Expect a valid enumeration value.
                'broad': {},
            },
        })

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

        https://docs.backpack.exchange/#tag/Assets

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        """
        response = self.publicGetApiV1Assets(params)
        #
        #     [
        #         {
        #             "coingeckoId": "jito-governance-token",
        #             "displayName": "Jito",
        #             "symbol": "JTO",
        #             "tokens": [
        #                 {
        #                     "blockchain": "Solana",
        #                     "contractAddress": "jtojtomepa8beP8AuQc6eXt5FriJwfFMwQx2v2f9mCL",
        #                     "depositEnabled": True,
        #                     "displayName": "Jito",
        #                     "maximumWithdrawal": null,
        #                     "minimumDeposit": "0.29",
        #                     "minimumWithdrawal": "0.58",
        #                     "withdrawEnabled": True,
        #                     "withdrawalFee": "0.29"
        #                 }
        #             ]
        #         }
        #         ...
        #     ]
        #
        result: dict = {}
        for i in range(0, len(response)):
            currecy = response[i]
            currencyId = self.safe_string(currecy, 'symbol')
            code = self.safe_currency_code(currencyId)
            networks = self.safe_list(currecy, 'tokens', [])
            parsedNetworks: dict = {}
            for j in range(0, len(networks)):
                network = networks[j]
                networkId = self.safe_string(network, 'blockchain')
                networkIdLowerCase = self.safe_string_lower(network, 'blockchain')
                networkCode = self.network_id_to_code(networkIdLowerCase)
                parsedNetworks[networkCode] = {
                    'id': networkId,
                    'network': networkCode,
                    'limits': {
                        'withdraw': {
                            'min': self.safe_number(network, 'minimumWithdrawal'),
                            'max': self.parse_number(self.omit_zero(self.safe_string(network, 'maximumWithdrawal'))),
                        },
                        'deposit': {
                            'min': self.safe_number(network, 'minimumDeposit'),
                            'max': None,
                        },
                    },
                    'active': None,
                    'deposit': self.safe_bool(network, 'depositEnabled'),
                    'withdraw': self.safe_bool(network, 'withdrawEnabled'),
                    'fee': self.safe_number(network, 'withdrawalFee'),
                    'precision': None,
                    'info': network,
                }
            active = None
            deposit = None
            withdraw = None
            if self.is_empty(parsedNetworks):  # if networks are not provided
                active = False
                deposit = False
                withdraw = False
            result[code] = self.safe_currency_structure({
                'id': currencyId,
                'code': code,
                'precision': None,
                'type': 'crypto',  # todo check if it is always crypto
                'name': self.safe_string(currecy, 'displayName'),
                'active': active,
                'deposit': deposit,
                'withdraw': withdraw,
                'fee': None,
                'limits': {
                    'deposit': {
                        'min': None,
                        'max': None,
                    },
                    'withdraw': {
                        'min': None,
                        'max': None,
                    },
                },
                'networks': parsedNetworks,
                'info': currecy,
            })
        return result

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

        https://docs.backpack.exchange/#tag/Markets/operation/get_markets

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        if self.options['adjustForTimeDifference']:
            self.load_time_difference()
        response = self.publicGetApiV1Markets(params)
        return self.parse_markets(response)

    def parse_market(self, market: dict) -> Market:
        #
        #     [
        #         {
        #             "baseSymbol": "SOL",
        #             "createdAt": "2025-01-21T06:34:54.691858",
        #             "filters": {
        #                 "price": {
        #                     "borrowmarketFeeMaxMultiplier": null,
        #                     "borrowmarketFeeMinMultiplier": null,
        #                     "maxImpactMultiplier": "1.03",
        #                     "maxMultiplier": "1.25",
        #                     "maxPrice": null,
        #                     "meanMarkPriceBand": {
        #                         "maxMultiplier": "1.15",
        #                         "minMultiplier": "0.9"
        #                     },
        #                     "meanPremiumBand": null,
        #                     "minImpactMultiplier": "0.97",
        #                     "minMultiplier": "0.75",
        #                     "minPrice": "0.01",
        #                     "tickSize": "0.01"
        #                 },
        #                 "quantity": {
        #                     "maxQuantity": null,
        #                     "minQuantity": "0.01",
        #                     "stepSize": "0.01"
        #                 }
        #             },
        #             "fundingInterval": 28800000,
        #             "fundingRateLowerBound": null,
        #             "fundingRateUpperBound": null,
        #             "imfFunction": null,
        #             "marketType": "SPOT",
        #             "mmfFunction": null,
        #             "openInterestLimit": "0",
        #             "orderBookState": "Open",
        #             "quoteSymbol": "USDC",
        #             "symbol": "SOL_USDC"
        #         },
        #         {
        #             "baseSymbol": "SOL",
        #             "createdAt": "2025-01-21T06:34:54.691858",
        #             "filters": {
        #                 "price": {
        #                     "borrowEntryFeeMaxMultiplier": null,
        #                     "borrowEntryFeeMinMultiplier": null,
        #                     "maxImpactMultiplier": "1.03",
        #                     "maxMultiplier": "1.25",
        #                     "maxPrice": "1000",
        #                     "meanMarkPriceBand": {
        #                         "maxMultiplier": "1.1",
        #                         "minMultiplier": "0.9"
        #                     },
        #                     "meanPremiumBand": {
        #                         "tolerancePct": "0.05"
        #                     },
        #                     "minImpactMultiplier": "0.97",
        #                     "minMultiplier": "0.75",
        #                     "minPrice": "0.01",
        #                     "tickSize": "0.01"
        #                 },
        #                 "quantity": {
        #                     "maxQuantity": null,
        #                     "minQuantity": "0.01",
        #                     "stepSize": "0.01"
        #                 }
        #             },
        #             "fundingInterval": "28800000",
        #             "fundingRateLowerBound": "-100",
        #             "fundingRateUpperBound": "100",
        #             "imfFunction": {
        #                 "base": "0.02",
        #                 "factor": "0.0001275",
        #                 "type": "sqrt"
        #             },
        #             "marketType": "PERP",
        #             "mmfFunction": {
        #                 "base": "0.0125",
        #                 "factor": "0.0000765",
        #                 "type": "sqrt"
        #             },
        #             "openInterestLimit": "4000000",
        #             "orderBookState": "Open",
        #             "quoteSymbol": "USDC",
        #             "symbol": "SOL_USDC_PERP"
        #         }
        #     ]
        #
        id = self.safe_string(market, 'symbol')
        baseId = self.safe_string(market, 'baseSymbol')
        quoteId = self.safe_string(market, 'quoteSymbol')
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        symbol = base + '/' + quote
        filters = self.safe_dict(market, 'filters', {})
        priceFilter = self.safe_dict(filters, 'price', {})
        maxPrice = self.safe_number(priceFilter, 'maxPrice')
        minPrice = self.safe_number(priceFilter, 'minPrice')
        pricePrecision = self.safe_number(priceFilter, 'tickSize')
        quantityFilter = self.safe_dict(filters, 'quantity', {})
        maxQuantity = self.safe_number(quantityFilter, 'maxQuantity')
        minQuantity = self.safe_number(quantityFilter, 'minQuantity')
        amountPrecision = self.safe_number(quantityFilter, 'stepSize')
        type: MarketType
        typeOfMarket = self.parse_market_type(self.safe_string(market, 'marketType'))
        linear: Bool = None
        inverse: Bool = None
        settle: Str = None
        settleId: Str = None
        contractSize: Num = None
        if typeOfMarket == 'spot':
            type = 'spot'
        elif typeOfMarket == 'swap':
            type = 'swap'
            linear = True
            inverse = False
            settleId = self.safe_string(market, 'quoteSymbol')
            settle = self.safe_currency_code(settleId)
            symbol += ':' + settle
            contractSize = 1
        orderBookState = self.safe_string(market, 'orderBookState')
        return self.safe_market_structure({
            'id': id,
            'symbol': symbol,
            'base': base,
            'quote': quote,
            'settle': settle,
            'baseId': baseId,
            'quoteId': quoteId,
            'settleId': settleId,
            'type': type,
            'spot': type == 'spot',
            'margin': type == 'spot',  # todo check if margin is supported for all markets
            'swap': type == 'swap',
            'future': False,
            'option': False,
            'active': orderBookState == 'Open',
            'contract': type != 'spot',
            'linear': linear,
            'inverse': inverse,
            'taker': None,  # todo check commission
            'maker': None,  # todo check commission
            'contractSize': contractSize,
            'expiry': None,
            'expiryDatetime': None,
            'strike': None,
            'optionType': None,
            'precision': {
                'amount': amountPrecision,
                'price': pricePrecision,
            },
            'limits': {
                'leverage': {
                    'min': None,
                    'max': None,
                },
                'amount': {
                    'min': minQuantity,
                    'max': maxQuantity,
                },
                'price': {
                    'min': minPrice,
                    'max': maxPrice,
                },
                'cost': {
                    'min': None,
                    'max': None,
                },
            },
            'created': self.parse8601(self.safe_string(market, 'createdAt')),
            'info': market,
        })

    def parse_market_type(self, type):
        types = {
            'SPOT': 'spot',
            'PERP': 'swap',
            # current types are described in the docs, but the exchange returns only 'SPOT' and 'PERP'
            # 'IPERP': 'swap',
            # 'DATED': 'swap',
            # 'PREDICTION': 'swap',
            # 'RFQ': 'swap',
        }
        return self.safe_string(types, type, type)

    def fetch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
        """

        https://docs.backpack.exchange/#tag/Markets/operation/get_tickers

        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
        :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        self.load_markets()
        request: dict = {}
        response = self.publicGetApiV1Tickers(self.extend(request, params))
        tickers = self.parse_tickers(response)
        return self.filter_by_array_tickers(tickers, 'symbol', symbols)

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

        https://docs.backpack.exchange/#tag/Markets/operation/get_ticker

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = self.publicGetApiV1Ticker(self.extend(request, params))
        return self.parse_ticker(response, market)

    def parse_ticker(self, ticker: dict, market: Market = None) -> Ticker:
        #
        # fetchTicker/fetchTickers
        #
        #     {
        #         "firstPrice": "327.38",
        #         "high": "337.99",
        #         "lastPrice": "317.14",
        #         "low": "300.01",
        #         "priceChange": "-10.24",
        #         "priceChangePercent": "-0.031279",
        #         "quoteVolume": "21584.32278",
        #         "symbol": "AAVE_USDC",
        #         "trades": "245",
        #         "volume": "65.823"
        #     }, ...
        #
        marketId = self.safe_string(ticker, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = self.safe_symbol(marketId, market)
        open = self.safe_string(ticker, 'firstPrice')
        last = self.safe_string(ticker, 'lastPrice')
        high = self.safe_string(ticker, 'high')
        low = self.safe_string(ticker, 'low')
        baseVolume = self.safe_string(ticker, 'volume')
        quoteVolume = self.safe_string(ticker, 'quoteVolume')
        percentage = self.safe_string(ticker, 'priceChangePercent')
        change = self.safe_string(ticker, 'priceChange')
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': None,
            'datetime': None,
            'high': high,
            'low': low,
            'bid': None,
            'bidVolume': None,
            'ask': None,
            'askVolume': None,
            'vwap': None,
            'open': open,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': change,
            'percentage': percentage,
            'average': None,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'markPrice': None,
            'indexPrice': None,
            'info': ticker,
        }, market)

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

        https://docs.backpack.exchange/#tag/Markets/operation/get_depth

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return(default 100, max 200)
        :param dict [params]: extra parameters specific to the bitteam api endpoint
        :returns dict: A dictionary of `order book structures <https://github.com/ccxt/ccxt/wiki/Manual#order-book-structure>` indexed by market symbols
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = self.publicGetApiV1Depth(self.extend(request, params))
        #
        #     {
        #         "asks": [
        #             ["118318.3","0.00633"],
        #             ["118567.2","0.08450"]
        #         ],
        #         "bids": [
        #             ["1.0","0.38647"],
        #             ["12.9","1.00000"]
        #         ],
        #         "lastUpdateId":"1504999670",
        #         "timestamp":1753102447307501
        #     }
        #
        microseconds = self.safe_integer(response, 'timestamp')
        timestamp = self.parse_to_int(microseconds / 1000)
        orderbook = self.parse_order_book(response, symbol, timestamp)
        orderbook['nonce'] = self.safe_integer(response, 'lastUpdateId')
        return orderbook

    def fetch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
        """
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://docs.backpack.exchange/#tag/Markets/operation/get_klines

        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in seconds of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch(default 100)
        :param dict [params]: extra parameters specific to the bitteam api endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        self.load_markets()
        market = self.market(symbol)
        interval = self.safe_string(self.timeframes, timeframe, timeframe)
        request: dict = {
            'symbol': market['id'],
            'interval': interval,
        }
        until: Int = None
        until, params = self.handle_option_and_params(params, 'fetchOHLCV', 'until')
        if until is not None:
            request['endTime'] = self.parse_to_int(until / 1000)  # convert milliseconds to seconds
        defaultLimit = 100
        if since is None:
            if limit is None:
                limit = defaultLimit
            duration = self.parse_timeframe(timeframe)
            endTime = self.parse_to_int(until / 1000) if until else self.seconds()
            startTime = endTime - (limit * duration)
            request['startTime'] = startTime
        else:
            request['startTime'] = self.parse_to_int(since / 1000)  # convert milliseconds to seconds
        price = self.safe_string(params, 'price')
        if price is not None:
            request['priceType'] = self.capitalize(price)
            params = self.omit(params, 'price')
        response = self.publicGetApiV1Klines(self.extend(request, params))
        return self.parse_ohlcvs(response, market, timeframe, since, limit)

    def parse_ohlcv(self, ohlcv, market: Market = None) -> list:
        #
        #     [
        #         {
        #             "close": "118294.6",
        #             "end": "2025-07-19 13:12:00",
        #             "high": "118297.6",
        #             "low": "118237.5",
        #             "open": "118238",
        #             "quoteVolume": "4106.558156",
        #             "start": "2025-07-19 13:09:00",
        #             "trades": "12",
        #             "volume": "0.03473"
        #         },
        #         ...
        #     ]
        #
        return [
            self.parse8601(self.safe_string(ohlcv, 'start')),
            self.safe_number(ohlcv, 'open'),
            self.safe_number(ohlcv, 'high'),
            self.safe_number(ohlcv, 'low'),
            self.safe_number(ohlcv, 'close'),
            self.safe_number(ohlcv, 'volume'),
        ]

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

        https://docs.backpack.exchange/#tag/Markets/operation/get_mark_prices

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        if market['spot']:
            raise BadRequest(self.id + ' fetchFundingRate() symbol does not support market ' + symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = self.publicGetApiV1MarkPrices(self.extend(request, params))
        data = self.safe_dict(response, 0, {})
        return self.parse_funding_rate(data, market)

    def parse_funding_rate(self, contract, market: Market = None) -> FundingRate:
        #
        #     {
        #         "fundingRate": "0.0001",
        #         "indexPrice": "118333.18643195",
        #         "markPrice": "118343.51853741",
        #         "nextFundingTimestamp": 1753113600000,
        #         "symbol": "BTC_USDC_PERP"
        #     }
        #
        marketId = self.safe_string(contract, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = self.safe_symbol(marketId, market)
        nextFundingTimestamp = self.safe_integer(contract, 'nextFundingTimestamp')
        return {
            'info': contract,
            'symbol': symbol,
            'markPrice': self.safe_number(contract, 'markPrice'),
            'indexPrice': self.safe_number(contract, 'indexPrice'),
            'interestRate': None,
            'estimatedSettlePrice': None,
            'timestamp': None,
            'datetime': None,
            'fundingRate': self.safe_number(contract, 'fundingRate'),
            'fundingTimestamp': None,
            'fundingDatetime': None,
            'nextFundingRate': None,
            'nextFundingTimestamp': nextFundingTimestamp,
            'nextFundingDatetime': self.iso8601(nextFundingTimestamp),
            'previousFundingRate': None,
            'previousFundingTimestamp': None,
            'previousFundingDatetime': None,
            'interval': '1h',
        }

    def fetch_open_interest(self, symbol: str, params={}):
        """
        Retrieves the open interest of a derivative trading pair

        https://docs.backpack.exchange/#tag/Markets/operation/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/#/?id=interest-history-structure:
        """
        self.load_markets()
        market = self.market(symbol)
        if market['spot']:
            raise BadRequest(self.id + ' fetchOpenInterest() symbol does not support market ' + symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = self.publicGetApiV1OpenInterest(self.extend(request, params))
        interest = self.safe_dict(response, 0, {})
        return self.parse_open_interest(interest, market)

    def parse_open_interest(self, interest, market: Market = None):
        #
        #     [
        #         {
        #             "openInterest": "1273.85214",
        #             "symbol": "BTC_USDC_PERP",
        #             "timestamp":1753105735301
        #         }
        #     ]
        #
        timestamp = self.safe_integer(interest, 'timestamp')
        openInterest = self.safe_number(interest, 'openInterest')
        return self.safe_open_interest({
            'symbol': market['symbol'],
            'openInterestAmount': None,
            'openInterestValue': openInterest,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'info': interest,
        }, market)

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

        https://docs.backpack.exchange/#tag/Markets/operation/get_funding_interval_rates

        :param str symbol: unified symbol of the market to fetch the funding rate history for
        :param int [since]: timestamp in ms of the earliest funding rate to fetch
        :param int [limit]: the maximum amount of funding rate structures
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchFundingRateHistory() requires a symbol argument')
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = min(limit, 1000)  # api maximum 1000
        response = self.publicGetApiV1FundingRates(self.extend(request, params))
        #
        #     [
        #         {
        #             "fundingRate": "0.0001",
        #             "intervalEndTimestamp": "2025-07-22T00:00:00",
        #             "symbol": "BTC_USDC_PERP"
        #         }
        #     ]
        #
        rates = []
        for i in range(0, len(response)):
            rate = response[i]
            datetime = self.safe_string(rate, 'intervalEndTimestamp')
            timestamp = self.parse8601(datetime)
            rates.append({
                'info': rate,
                'symbol': market['symbol'],
                'fundingRate': self.safe_number(rate, 'fundingRate'),
                'timestamp': timestamp,
                'datetime': datetime,
            })
        sorted = self.sort_by(rates, 'timestamp')
        return self.filter_by_symbol_since_limit(sorted, market['symbol'], since, limit)

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

        https://docs.backpack.exchange/#tag/Trades/operation/get_recent_trades
        https://docs.backpack.exchange/#tag/Trades/operation/get_historical_trades

        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.offset]: the number of trades to skip, default is 0
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = min(limit, 1000)  # api maximum 1000
        response = None
        offset = self.safe_integer(params, 'offset')
        if offset is not None:
            response = self.publicGetApiV1TradesHistory(self.extend(request, params))
        else:
            response = self.publicGetApiV1Trades(self.extend(request, params))
        return self.parse_trades(response, market, since, limit)

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

        https://docs.backpack.exchange/#tag/History/operation/get_fills

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades structures to retrieve(default 100, max 1000)
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch trades for
        :param str [params.fillType]: 'User'(default) 'BookLiquidation' or 'Adl' or 'Backstop' or 'Liquidation' or 'AllLiquidation' or 'CollateralConversion' or 'CollateralConversionAndSpotLiquidation'
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        """
        self.load_markets()
        request: dict = {}
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if since is not None:
            request['from'] = since
        if limit is not None:
            request['limit'] = limit
        until = self.safe_integer(params, 'until')
        if until is not None:
            params = self.omit(params, ['until'])
            request['to'] = until
        fillType = self.safe_string(params, 'fillType')
        if fillType is None:
            request['fillType'] = 'User'  # default
        response = self.privateGetWapiV1HistoryFills(self.extend(request, params))
        return self.parse_trades(response, market, since, limit)

    def parse_trade(self, trade: dict, market: Market = None) -> Trade:
        #
        # fetchTrades
        #     {
        #         "id": 8721564,
        #         "isBuyerMaker": False,
        #         "price": "117427.6",
        #         "quantity": "0.00016",
        #         "quoteQuantity": "18.788416",
        #         "timestamp": 1753123916818
        #     }
        #
        # fetchMyTrades
        #     {
        #         "clientId": null,
        #         "fee": "0.004974",
        #         "feeSymbol": "USDC",
        #         "isMaker": False,
        #         "orderId": "4238907375",
        #         "price": "3826.15",
        #         "quantity": "0.0026",
        #         "side": "Bid",
        #         "symbol": "ETH_USDC_PERP",
        #         "systemOrderType": null,
        #         "timestamp": "2025-07-27T17:39:00.092",
        #         "tradeId": 9748827
        #     }
        #
        id = self.safe_string_2(trade, 'id', 'tradeId')
        marketId = self.safe_string(trade, 'symbol')
        market = self.safe_market(marketId, market)
        price = self.safe_string(trade, 'price')
        amount = self.safe_string(trade, 'quantity')
        isMaker = self.safe_bool(trade, 'isMaker')
        takerOrMaker = 'maker' if isMaker else 'taker'
        orderId = self.safe_string(trade, 'orderId')
        side = self.parse_order_side(self.safe_string(trade, 'side'))
        fee = None
        feeAmount = self.safe_string(trade, 'fee')
        timestamp = self.safe_integer(trade, 'timestamp')
        if feeAmount is not None:
            # if fetchMyTrades
            datetime = self.safe_string(trade, 'timestamp')
            timestamp = self.parse8601(datetime)
        feeSymbol = self.safe_currency_code(self.safe_string(trade, 'feeSymbol'))
        if feeAmount is not None:
            fee = {
                'cost': feeAmount,
                'currency': feeSymbol,
                'rate': None,
            }
        return self.safe_trade({
            'info': trade,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': market['symbol'],
            'id': id,
            'order': orderId,
            'type': None,
            'side': side,
            'takerOrMaker': takerOrMaker,
            'price': price,
            'amount': amount,
            'cost': None,
            'fee': fee,
        }, market)

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

        https://docs.backpack.exchange/#tag/System/operation/get_status

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `status structure <https://docs.ccxt.com/#/?id=exchange-status-structure>`
        """
        response = self.publicGetApiV1Status(params)
        #
        #     {
        #         "message":null,
        #         "status":"Ok"
        #     }
        #
        status = self.safe_string(response, 'status')
        return {
            'status': status.lower(),
            'updated': None,
            'eta': None,
            'url': None,
            'info': response,
        }

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

        https://developer-pro.bitmart.com/en/spot/#get-system-time

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        """
        response = self.publicGetApiV1Time(params)
        #
        #     1753131712992
        #
        return self.safe_integer(response, 0, self.milliseconds())

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

        https://docs.backpack.exchange/#tag/Capital/operation/get_balances

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        """
        self.load_markets()
        response = self.privateGetApiV1Capital(params)
        return self.parse_balance(response)

    def parse_balance(self, response) -> Balances:
        #
        #     {
        #         "USDC": {
        #             "available": "120",
        #             "locked": "0",
        #             "staked": "0"
        #         }
        #     }
        #
        balanceKeys = list(response.keys())
        result: dict = {}
        for i in range(0, len(balanceKeys)):
            id = balanceKeys[i]
            code = self.safe_currency_code(id)
            balance = response[id]
            account = self.account()
            locked = self.safe_string(balance, 'locked')
            staked = self.safe_string(balance, 'staked')
            used = Precise.string_add(locked, staked)
            account['free'] = self.safe_string(balance, 'available')
            account['used'] = used
            result[code] = account
        return self.safe_balance(result)

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

        https://docs.backpack.exchange/#tag/Capital/operation/get_deposits

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch deposits for
        :param int [limit]: the maximum number of deposits structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch entries for
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        """
        self.load_markets()
        request: dict = {
        }
        currency: Currency = None
        if code is not None:
            currency = self.currency(code)
        if since is not None:
            request['from'] = since
        if limit is not None:
            request['limit'] = limit  # default 100, max 1000
        until: Int = None
        until, params = self.handle_option_and_params(params, 'fetchDeposits', 'until')
        if until is not None:
            request['endTime'] = until
        response = self.privateGetWapiV1CapitalDeposits(self.extend(request, params))
        return self.parse_transactions(response, currency, since, limit)

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

        https://docs.backpack.exchange/#tag/Capital/operation/get_withdrawals

        :param str code: unified currency code of the currency transferred
        :param int [since]: the earliest time in ms to fetch transfers for(default 24 hours ago)
        :param int [limit]: the maximum number of transfer structures to retrieve(default 50, max 200)
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch transfers for(default time now)
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        """
        self.load_markets()
        request: dict = {}
        currency: Currency = None
        if code is not None:
            currency = self.currency(code)
        if since is not None:
            request['from'] = since
        if limit is not None:
            request['limit'] = limit
        until: Int = None
        until, params = self.handle_option_and_params(params, 'fetchWithdrawals', 'until')
        if until is not None:
            request['to'] = until
        response = self.privateGetWapiV1CapitalWithdrawals(self.extend(request, params))
        return self.parse_transactions(response, currency, since, limit)

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

        https://docs.backpack.exchange/#tag/Capital/operation/request_withdrawal

        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str tag:
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str params['network']: the network to withdraw on(mandatory)
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        """
        self.load_markets()
        currency = self.currency(code)
        request: dict = {
            'symbol': currency['id'],
            'quantity': self.number_to_string(amount),
            'address': address,
        }
        if tag is not None:
            request['clientId'] = tag  # memo or tag
        networkCode, query = self.handle_network_code_and_params(params)
        networkId = self.network_code_to_id(networkCode)
        if networkId is None:
            raise BadRequest(self.id + ' withdraw() requires a network parameter')
        request['blockchain'] = networkId
        response = self.privatePostWapiV1CapitalWithdrawals(self.extend(request, query))
        return self.parse_transaction(response, currency)

    def parse_transaction(self, transaction, currency: Currency = None) -> Transaction:
        #
        # fetchDeposits
        #     [
        #         {
        #             "createdAt": "2025-07-23T13:55:54.267",
        #             "fiatAmount": null,
        #             "fiatCurrency": null,
        #             "fromAddress": "0x2e3ab3e88a7dbdc763aadf5b28c18fb085af420a",
        #             "id": 6695353,
        #             "institutionBic": null,
        #             "platformMemo": null,
        #             "quantity": "120",
        #             "source": "ethereum",
        #             "status": "confirmed",
        #             "symbol": "USDC",
        #             "toAddress": "0xfBe7CbfCde93c8a4204a4be6B56732Eb32690170",
        #             "transactionHash": "0x58edaac415398d617b34c6673fffcaf0024990d5700565030119db5cbf3765d1"
        #         }
        #     ]
        #
        # withdraw
        #     {
        #         "accountIdentifier": null,
        #         "bankIdentifier": null,
        #         "bankName": null,
        #         "blockchain": "Ethereum",
        #         "clientId": null,
        #         "createdAt": "2025-08-13T19:27:13.817",
        #         "fee": "3",
        #         "fiatFee": null,
        #         "fiatState": null,
        #         "fiatSymbol": null,
        #         "id": 5479929,
        #         "identifier": null,
        #         "isInternal": False,
        #         "providerId": null,
        #         "quantity": "10",
        #         "status": "pending",
        #         "subaccountId": null,
        #         "symbol": "USDC",
        #         "toAddress": "0x0ad42b8e602c2d3d475ae52d678cf63d84ab2749",
        #         "transactionHash": null,
        #         "triggerAt": null
        #     }
        #
        # fetchWithdrawals
        #     [
        #         {
        #             "accountIdentifier": null,
        #             "bankIdentifier": null,
        #             "bankName": null,
        #             "blockchain": "Ethereum",
        #             "clientId": null,
        #             "createdAt": "2025-08-13T19:27:13.817",
        #             "fee": "3",
        #             "fiatFee": null,
        #             "fiatState": null,
        #             "fiatSymbol": null,
        #             "id": 5479929,
        #             "identifier": null,
        #             "isInternal": False,
        #             "providerId": null,
        #             "quantity": "10",
        #             "status": "confirmed",
        #             "subaccountId": null,
        #             "symbol": "USDC",
        #             "toAddress": "0x0ad42b8e602c2d3d475ae52d678cf63d84ab2749",
        #             "transactionHash": "0x658b6d082af4afa0d3cf85caf344ff7c19d980117726bf193b00d8850f8746a1",
        #             "triggerAt": null
        #         }
        #     ]
        #
        status = self.parse_transaction_status(self.safe_string(transaction, 'status'))
        id = self.safe_string(transaction, 'id')
        txid = self.safe_string(transaction, 'transactionHash')
        coin = self.safe_string(transaction, 'symbol')
        code = self.safe_currency_code(coin, currency)
        timestamp = self.parse8601(self.safe_string(transaction, 'createdAt'))
        amount = self.safe_number(transaction, 'quantity')
        networkId = self.safe_string_lower_2(transaction, 'source', 'blockchain')
        network = self.network_id_to_code(networkId)
        addressTo = self.safe_string(transaction, 'toAddress')
        addressFrom = self.safe_string(transaction, 'fromAddress')
        tag = self.safe_string(transaction, 'platformMemo')
        feeCost = self.safe_number(transaction, 'fee')
        internal = self.safe_bool(transaction, 'isInternal', False)
        fee = None
        if feeCost is not None:
            fee = {
                'cost': feeCost,
                'currency': code,
            }
        return {
            'info': transaction,
            'id': id,
            'txid': txid,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'network': network,
            'address': None,
            'addressTo': addressTo,
            'addressFrom': addressFrom,
            'tag': tag,
            'tagTo': None,
            'tagFrom': None,
            'type': None,
            'amount': amount,
            'currency': code,
            'status': status,
            'updated': None,
            'internal': internal,
            'comment': None,
            'fee': fee,
        }

    def parse_transaction_status(self, status: Str):
        statuses: dict = {
            'cancelled': 'cancelled',
            'confirmed': 'ok',
            'declined': 'declined',
            'expired': 'expired',
            'initiated': 'initiated',
            'pending': 'pending',
            'refunded': 'refunded',
            'information required': 'pending',
        }
        return self.safe_string(statuses, status, status)

    def fetch_deposit_address(self, code: str, params={}) -> DepositAddress:
        """
        fetch the deposit address for a currency associated with self account

        https://docs.backpack.exchange/#tag/Capital/operation/get_deposit_address

        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.networkCode]: the network to fetch the deposit address(mandatory)
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        """
        self.load_markets()
        networkCode = None
        networkCode, params = self.handle_network_code_and_params(params)
        if networkCode is None:
            raise ArgumentsRequired(self.id + ' fetchDepositAddress() requires a network parameter, see https://docs.ccxt.com/#/?id=network-codes')
        currency = self.currency(code)
        request: dict = {
            'blockchain': self.network_code_to_id(networkCode),
        }
        response = self.privateGetWapiV1CapitalDepositAddress(self.extend(request, params))
        return self.parse_deposit_address(response, currency)

    def parse_deposit_address(self, depositAddress, currency: Currency = None) -> DepositAddress:
        #
        #     {
        #         "address": "0xfBe7CbfCde93c8a4204a4be6B56732Eb32690170"
        #     }
        #
        address = self.safe_string(depositAddress, 'address')
        currencyId = self.safe_string(depositAddress, 'currency')
        currency = self.safe_currency(currencyId, currency)
        return {
            'info': depositAddress,
            'currency': currency['code'],
            'network': None,  # network is not returned by the API
            'address': address,
            'tag': None,
        }

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

        https://docs.backpack.exchange/#tag/Order/operation/execute_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 [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 exchange API endpoint
        :param float [params.cost]: *market orders only* the cost of the order in units of the quote currency(could be used instead of amount)
        :param int [params.clientOrderId]: a unique id for the order
        :param boolean [params.postOnly]: True to place a post only order
        :param str [params.timeInForce]: 'GTC', 'IOC', 'FOK' or 'PO'
        :param bool [params.reduceOnly]: *contract only* Indicates if self order is to reduce the size of a position
        :param str [params.selfTradePrevention]: one of EXPIRE_MAKER, EXPIRE_TAKER or EXPIRE_BOTH
        :param bool [params.autoLend]: *spot margin only* if True then the order can lend
        :param bool [params.autoLendRedeem]: *spot margin only* if True then the order can redeem a lend if required
        :param bool [params.autoBorrow]: *spot margin only* if True then the order can borrow
        :param bool [params.autoBorrowRepay]: *spot margin only* if True then the order can repay a borrow
        :param float [params.triggerPrice]: the price that a trigger order is triggered at
        :param dict [params.takeProfit]: *swap markets only - takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered
        :param float [params.takeProfit.triggerPrice]: take profit trigger price
        :param float [params.takeProfit.price]: take profit order price(if not provided the order will be a market order)
        :param dict [params.stopLoss]: *swap markets only - stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered
        :param float [params.stopLoss.triggerPrice]: stop loss trigger price
        :param float [params.stopLoss.price]: stop loss order price(if not provided the order will be a market order)
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        orderRequest = self.create_order_request(symbol, type, side, amount, price, params)
        response = self.privatePostApiV1Order(orderRequest)
        return self.parse_order(response, market)

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

        https://docs.backpack.exchange/#tag/Order/operation/execute_order_batch

        :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        ordersRequests = []
        for i in range(0, len(orders)):
            rawOrder = orders[i]
            marketId = self.safe_string(rawOrder, 'symbol')
            type = self.safe_string(rawOrder, 'type')
            side = self.safe_string(rawOrder, 'side')
            amount = self.safe_number(rawOrder, 'amount')
            price = self.safe_number(rawOrder, 'price')
            orderParams = self.safe_dict(rawOrder, 'params', {})
            extendedParams = self.extend(orderParams, params)  # the request does not accept extra params since it's a list, so we're extending each order with the common params
            orderRequest = self.create_order_request(marketId, type, side, amount, price, extendedParams)
            ordersRequests.append(orderRequest)
        response = self.privatePostApiV1Orders(ordersRequests)
        return self.parse_orders(response)

    def create_order_request(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}):
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
            'side': self.encode_order_side(side),
            'orderType': self.capitalize(type),
        }
        triggerPrice = self.safe_string(params, 'triggerPrice')
        isTriggerOrder = triggerPrice is not None
        quantityKey = 'triggerQuantity' if isTriggerOrder else 'quantity'
        # handle basic limit/market order types
        if type == 'limit':
            request['price'] = self.price_to_precision(symbol, price)
            request[quantityKey] = self.amount_to_precision(symbol, amount)
        elif type == 'market':
            cost = self.safe_string_2(params, 'cost', 'quoteQuantity')
            if cost is not None:
                request['quoteQuantity'] = self.cost_to_precision(symbol, cost)
                params = self.omit(params, ['cost', 'quoteQuantity'])
            else:
                request[quantityKey] = self.amount_to_precision(symbol, amount)
        # trigger orders
        if isTriggerOrder:
            request['triggerPrice'] = self.price_to_precision(symbol, triggerPrice)
            params = self.omit(params, 'triggerPrice')
        clientOrderId = self.safe_integer(params, 'clientOrderId')  # the exchange requires uint
        if clientOrderId is not None:
            request['clientId'] = clientOrderId
            params = self.omit(params, 'clientOrderId')
        postOnly = False
        postOnly, params = self.handle_post_only(type == 'market', False, params)
        if postOnly:
            params['postOnly'] = True
        takeProfit = self.safe_dict(params, 'takeProfit')
        if takeProfit is not None:
            takeProfitTriggerPrice = self.safe_string(takeProfit, 'triggerPrice')
            if takeProfitTriggerPrice is not None:
                request['takeProfitTriggerPrice'] = self.price_to_precision(symbol, takeProfitTriggerPrice)
            takeProfitPrice = self.safe_string(takeProfit, 'price')
            if takeProfitPrice is not None:
                request['takeProfitLimitPrice'] = self.price_to_precision(symbol, takeProfitPrice)
            params = self.omit(params, 'takeProfit')
        stopLoss = self.safe_dict(params, 'stopLoss')
        if stopLoss is not None:
            stopLossTriggerPrice = self.safe_string(stopLoss, 'triggerPrice')
            if stopLossTriggerPrice is not None:
                request['stopLossTriggerPrice'] = self.price_to_precision(symbol, stopLossTriggerPrice)
            stopLossPrice = self.safe_string(stopLoss, 'price')
            if stopLossPrice is not None:
                request['stopLossLimitPrice'] = self.price_to_precision(symbol, stopLossPrice)
            params = self.omit(params, 'stopLoss')
        selfTradePrevention = None
        selfTradePrevention, params = self.handle_option_and_params(params, 'createOrder', 'selfTradePrevention')
        if selfTradePrevention is not None:
            if selfTradePrevention == 'EXPIRE_MAKER':
                request['selfTradePrevention'] = 'RejectMaker'
            elif selfTradePrevention == 'EXPIRE_TAKER':
                request['selfTradePrevention'] = 'RejectTaker'
            elif selfTradePrevention == 'EXPIRE_BOTH':
                request['selfTradePrevention'] = 'RejectBoth'
        return self.extend(request, params)

    def encode_order_side(self, side):
        sides: dict = {
            'buy': 'Bid',
            'sell': 'Ask',
        }
        return self.safe_string(sides, side, side)

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

        https://docs.backpack.exchange/#tag/Order/operation/get_open_orders

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of open orders structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        request: dict = {}
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        response = self.privateGetApiV1Orders(self.extend(request, params))
        return self.parse_orders(response, market, since, limit)

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

        https://docs.backpack.exchange/#tag/Order/operation/get_order

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

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

        https://docs.backpack.exchange/#tag/Order/operation/cancel_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 exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        if symbol is None:
            raise ArgumentsRequired(self.id + ' cancelOrder() requires a symbol argument')
        market = self.market(symbol)
        request: dict = {
            'orderId': id,
            'symbol': market['id'],
        }
        response = self.privateDeleteApiV1Order(self.extend(request, params))
        return self.parse_order(response)

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

        https://docs.backpack.exchange/#tag/Order/operation/cancel_open_orders

        :param str symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        if symbol is None:
            raise ArgumentsRequired(self.id + ' cancelOrder() requires a symbol argument')
        market = self.market(symbol)
        request: dict = {
            'symbol': market['id'],
        }
        response = self.privateDeleteApiV1Orders(self.extend(request, params))
        return self.parse_orders(response, market)

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

        https://docs.backpack.exchange/#tag/History/operation/get_order_history

        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of  orde structures to retrieve(default 100, max 1000)
        :param dict [params]: extra parameters specific to the bitteam api endpoint
        :returns Order[]: a list of `order structures <https://github.com/ccxt/ccxt/wiki/Manual#order-structure>`
        """
        self.load_markets()
        request: dict = {}
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if limit is not None:
            request['limit'] = limit
        response = self.privateGetWapiV1HistoryOrders(self.extend(request, params))
        return self.parse_orders(response, market, since, limit)

    def parse_order(self, order: dict, market: Market = None) -> Order:
        #
        #     {
        #         "clientId": null,
        #         "createdAt": 1753624283415,
        #         "executedQuantity": "0.001",
        #         "executedQuoteQuantity": "3.81428",
        #         "id": "4227701917",
        #         "orderType": "Market",
        #         "quantity": "0.001",
        #         "quoteQuantity": "3.82",
        #         "reduceOnly": null,
        #         "relatedOrderId": null,
        #         "selfTradePrevention": "RejectTaker",
        #         "side": "Bid",
        #         "status": "Filled",
        #         "stopLossLimitPrice": null,
        #         "stopLossTriggerBy": null,
        #         "stopLossTriggerPrice": null,
        #         "strategyId": null,
        #         "symbol": "ETH_USDC",
        #         "takeProfitLimitPrice": null,
        #         "takeProfitTriggerBy": null,
        #         "takeProfitTriggerPrice": null,
        #         "timeInForce": "GTC",
        #         "triggerBy": null,
        #         "triggerPrice": null,
        #         "triggerQuantity": null,
        #         "triggeredAt": null
        #     }
        #
        # fetchOpenOrders
        #     {
        #         "clientId": 123456789,
        #         "createdAt": 1753626206762,
        #         "executedQuantity": "0",
        #         "executedQuoteQuantity": "0",
        #         "id": "4228978331",
        #         "orderType": "Limit",
        #         "postOnly": True,
        #         "price": "3000",
        #         "quantity": "0.001",
        #         "reduceOnly": null,
        #         "relatedOrderId": null,
        #         "selfTradePrevention": "RejectTaker",
        #         "side": "Bid",
        #         "status": "New",
        #         "stopLossLimitPrice": null,
        #         "stopLossTriggerBy": null,
        #         "stopLossTriggerPrice": null,
        #         "strategyId": null,
        #         "symbol": "ETH_USDC",
        #         "takeProfitLimitPrice": null,
        #         "takeProfitTriggerBy": null,
        #         "takeProfitTriggerPrice": null,
        #         "timeInForce": "GTC",
        #         "triggerBy": null,
        #         "triggerPrice": null,
        #         "triggerQuantity": null,
        #         "triggeredAt": null
        #     }
        #
        # fetchOrders
        #     {
        #         "clientId": null,
        #         "createdAt": "2025-07-27T18:05:40.897",
        #         "executedQuantity": "0",
        #         "executedQuoteQuantity": "0",
        #         "expiryReason": null,
        #         "id": "4239996998",
        #         "orderType": "Limit",
        #         "postOnly": False,
        #         "price": "4500",
        #         "quantity": null,
        #         "quoteQuantity": null,
        #         "selfTradePrevention": "RejectTaker",
        #         "side": "Ask",
        #         "status": "Cancelled",
        #         "stopLossLimitPrice": null,
        #         "stopLossTriggerBy": null,
        #         "stopLossTriggerPrice": null,
        #         "strategyId": null,
        #         "symbol": "ETH_USDC",
        #         "systemOrderType": null,
        #         "takeProfitLimitPrice": null,
        #         "takeProfitTriggerBy": null,
        #         "takeProfitTriggerPrice": null,
        #         "timeInForce": "GTC",
        #         "triggerBy": null,
        #         "triggerPrice": "4300",
        #         "triggerQuantity": "0.001"
        #     }
        #
        timestamp = self.safe_integer(order, 'createdAt')
        timestamp2 = self.parse8601(self.safe_string(order, 'createdAt'))
        if timestamp2 is not None:
            timestamp = timestamp2
        id = self.safe_string(order, 'id')
        clientOrderId = self.safe_string(order, 'clientId')
        symbol = self.safe_symbol(self.safe_string(order, 'symbol'), market)
        type = self.safe_string_lower(order, 'orderType')
        timeInForce = self.safe_string(order, 'timeInForce')
        side = self.parse_order_side(self.safe_string(order, 'side'))
        amount = self.safe_string_2(order, 'quantity', 'triggerQuantity')
        price = self.safe_string(order, 'price')
        cost = self.safe_string(order, 'executedQuoteQuantity')
        status = self.parse_order_status(self.safe_string(order, 'status'))
        triggerPrice = self.safe_string(order, 'triggerPrice')
        filled = self.safe_string(order, 'executedQuantity')
        reduceOnly = self.safe_bool(order, 'reduceOnly')
        postOnly = self.safe_bool(order, 'postOnly')
        stopLossPrice = self.safe_string_2(order, 'stopLossLimitPrice', 'stopLossTriggerPrice')
        takeProfitPrice = self.safe_string_2(order, 'takeProfitLimitPrice', 'takeProfitTriggerPrice')
        return self.safe_order({
            'info': order,
            'id': id,
            'clientOrderId': clientOrderId,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': None,
            'symbol': symbol,
            'type': type,
            'timeInForce': timeInForce,
            'postOnly': postOnly,
            'reduceOnly': reduceOnly,
            'side': side,
            'price': price,
            'triggerPrice': triggerPrice,
            'stopLossPrice': stopLossPrice,
            'takeProfitPrice': takeProfitPrice,
            'amount': amount,
            'cost': cost,
            'average': None,
            'filled': filled,
            'remaining': None,
            'status': status,
            'fee': None,
            'trades': None,
        }, market)

    def parse_order_status(self, status: Str):
        statuses: dict = {
            'New': 'open',
            'Filled': 'closed',
            'Cancelled': 'canceled',
            'Expired': 'canceled',
            'PartiallyFilled': 'open',
            'TriggerPending': 'open',
            'TriggerFailed': 'rejected',
        }
        return self.safe_string(statuses, status, status)

    def parse_order_side(self, side: Str):
        sides: dict = {
            'Bid': 'buy',
            'Ask': 'sell',
        }
        return self.safe_string(sides, side, side)

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

        https://docs.backpack.exchange/#tag/Futures/operation/get_positions

        :param str[]|None symbols: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        """
        self.load_markets()
        response = self.privateGetApiV1Position(params)
        positions = self.parse_positions(response)
        if self.is_empty(symbols):
            return positions
        symbols = self.market_symbols(symbols)
        return self.filter_by_array_positions(positions, 'symbol', symbols, False)

    def parse_position(self, position: dict, market: Market = None):
        #
        # fetchPositions
        #     {
        #         "breakEvenPrice": "3831.3630555555555555555555556",
        #         "cumulativeFundingPayment": "-0.009218",
        #         "cumulativeInterest": "0",
        #         "entryPrice": "3826.8888888888888888888888889",
        #         "estLiquidationPrice": "0",
        #         "imf": "0.02",
        #         "imfFunction": {
        #             "base": "0.02",
        #             "factor": "0.0000935",
        #             "type": "sqrt"
        #         },
        #         "markPrice": "3787.46813304",
        #         "mmf": "0.0125",
        #         "mmfFunction": {
        #             "base": "0.0125",
        #             "factor": "0.0000561",
        #             "type": "sqrt"
        #         },
        #         "netCost": "13.7768",
        #         "netExposureNotional": "13.634885278944",
        #         "netExposureQuantity": "0.0036",
        #         "netQuantity": "0.0036",
        #         "pnlRealized": "0",
        #         "pnlUnrealized": "-0.141914",
        #         "positionId": "4238420454",
        #         "subaccountId": null,
        #         "symbol": "ETH_USDC_PERP",
        #         "userId":1813870
        #     }
        #
        #
        id = self.safe_string(position, 'positionId')
        marketId = self.safe_string(position, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = market['symbol']
        entryPrice = self.safe_string(position, 'entryPrice')
        markPrice = self.safe_string(position, 'markPrice')
        netCost = self.safe_string(position, 'netCost')
        hedged = False
        side = 'long'
        if Precise.string_lt(netCost, '0'):
            side = 'short'
        if netCost is None:
            hedged = None
            side = None
        unrealizedPnl = self.safe_string(position, 'pnlUnrealized')
        realizedPnl = self.safe_string(position, 'pnlRealized')
        liquidationPrice = self.safe_string(position, 'estLiquidationPrice')
        return self.safe_position({
            'info': position,
            'id': id,
            'symbol': symbol,
            'timestamp': self.parse8601(self.safe_string(position, 'timestamp')),
            'datetime': self.iso8601(self.parse8601(self.safe_string(position, 'timestamp'))),
            'lastUpdateTimestamp': None,
            'hedged': hedged,
            'side': side,
            'contracts': self.safe_string(position, 'netExposureQuantity'),
            'contractSize': None,
            'entryPrice': entryPrice,
            'markPrice': markPrice,
            'lastPrice': None,
            'notional': Precise.string_abs(netCost),
            'leverage': None,
            'collateral': None,
            'initialMargin': None,
            'initialMarginPercentage': self.safe_string(position, 'imf'),
            'maintenanceMargin': None,
            'maintenanceMarginPercentage': self.safe_string(position, 'mmf'),
            'realizedPnl': realizedPnl,
            'unrealizedPnl': unrealizedPnl,
            'liquidationPrice': liquidationPrice,
            'marginMode': None,
            'marginRatio': None,
            'percentage': None,
            'stopLossPrice': None,
            'takeProfitPrice': None,
        })

    def fetch_funding_history(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}):
        """
        fetches the history of funding payments

        https://docs.backpack.exchange/#tag/History/operation/get_funding_payments

        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch(default 24 hours ago)
        :param int [limit]: the maximum amount of trades to fetch(default 200, max 500)
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest trade to fetch(default now)
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        """
        self.load_markets()
        request: dict = {}
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if limit is not None:
            request['limit'] = limit
        response = self.privateGetWapiV1HistoryFunding(self.extend(request, params))
        return self.parse_incomes(response, market, since, limit)

    def parse_income(self, income, market: Market = None):
        #
        #     {
        #         "fundingRate": "0.0001",
        #         "intervalEndTimestamp": "2025-08-01T16:00:00",
        #         "quantity": "-0.001301",
        #         "subaccountId": 0,
        #         "symbol": "ETH_USDC_PERP",
        #         "userId": 1813870
        #     }
        #
        marketId = self.safe_string(income, 'symbol')
        symbol = self.safe_symbol(marketId, market)
        amount = self.safe_number(income, 'quantity')
        id = self.safe_string(income, 'userId')
        timestamp = self.parse8601(self.safe_string(income, 'intervalEndTimestamp'))
        rate = self.safe_number(income, 'fundingRate')
        return {
            'info': income,
            'symbol': symbol,
            'code': None,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'id': id,
            'amount': amount,
            'rate': rate,
        }

    def nonce(self):
        return self.milliseconds() - self.options['timeDifference']

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        endpoint = '/' + path
        url = self.urls['api'][api]
        sortedParams = params if isinstance(params, list) else self.keysort(params)
        if api == 'private':
            self.check_required_credentials()
            ts = str(self.nonce())
            recvWindow = self.safe_string_2(self.options, 'recvWindow', 'X-Window', '5000')
            optionInstructions = self.safe_dict(self.options, 'instructions', {})
            optionPathInstructions = self.safe_dict(optionInstructions, path, {})
            instruction = self.safe_string(optionPathInstructions, method, '')
            payload = ''
            if (path == 'api/v1/orders') and (method == 'POST'):  # for createOrders
                payload = self.generate_batch_payload(sortedParams, ts, recvWindow, instruction)
            else:
                queryString = self.urlencode(sortedParams)
                if len(queryString) > 0:
                    queryString += '&'
                payload = 'instruction=' + instruction + '&' + queryString + 'timestamp=' + ts + '&window=' + recvWindow
            secretBytes = self.base64_to_binary(self.secret)
            seed = self.array_slice(secretBytes, 0, 32)
            signature = self.eddsa(self.encode(payload), seed, 'ed25519')
            headers = {
                'X-Timestamp': ts,
                'X-Window': recvWindow,
                'X-API-Key': self.apiKey,
                'X-Signature': signature,
                'X-Broker-Id': '1400',
            }
            if method != 'GET':
                body = self.json(sortedParams)
                headers['Content-Type'] = 'application/json'
        if method == 'GET':
            query = self.urlencode(sortedParams)
            if len(query) != 0:
                endpoint += '?' + query
        url += endpoint
        return {'url': url, 'method': method, 'body': body, 'headers': headers}

    def generate_batch_payload(self, params, ts, recvWindow, instruction):
        payload = ''
        for i in range(0, len(params)):
            order = self.safe_dict(params, i, {})
            sortedOrder = self.keysort(order)
            orderQuery = self.urlencode(sortedOrder)
            payload += 'instruction=' + instruction + '&' + orderQuery + '&'
            if i == (len(params) - 1):
                payload += 'timestamp=' + ts + '&window=' + recvWindow
        return payload

    def handle_errors(self, code: int, reason: str, url: str, method: str, headers: dict, body: str, response, requestHeaders, requestBody):
        if response is None:
            return None  # fallback to default error handler
        #
        # {"code":"INVALID_ORDER","message":"Invalid order"}
        # {"code":"INVALID_CLIENT_REQUEST","message":"Must specify both `triggerPrice` and `triggerQuantity` or neither"}
        #
        errorCode = self.safe_string(response, 'code')
        message = self.safe_string(response, 'message')
        if errorCode is not None:
            feedback = self.id + ' ' + body
            self.throw_exactly_matched_exception(self.exceptions['exact'], errorCode, feedback)
            self.throw_exactly_matched_exception(self.exceptions['exact'], message, feedback)
            self.throw_broadly_matched_exception(self.exceptions['broad'], message, feedback)
            raise ExchangeError(feedback)  # unknown message
        return None
