
    E#in|                    X   S SK Jr  S SKJr  S SKJrJrJrJrJ	r	J
r
JrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJr  S SKJr  S SKJr  S SKJ r   S SKJ!r!  S SKJ"r"  S S	KJ#r#  S S
KJ$r$  S SKJ%r%  S SKJ&r&  S SKJ'r'  S SKJ(r(  S SKJ)r)  S SKJ*r*  S SKJ+r+  S SK,J-r-  S SK.J/r/   " S S\\5      r0g)    )Exchange)ImplicitAPI)AnyBalancesBool
CurrenciesCurrencyDepositAddressIntMarket
MarketTypeNumOrder	OrderBookOrderRequest	OrderSide	OrderTypePositionStrStringsTickerTickersFundingRateTradeTransaction)List)ExchangeError)AuthenticationError)ArgumentsRequired)
BadRequest)	BadSymbol)OperationRejected)InsufficientFunds)InvalidOrder)OperationFailed)NetworkError)RateLimitExceeded)ExchangeNotAvailable)RequestTimeout)	TICK_SIZE)Precisec                     ^  \ rS rSrS\4U 4S jjr0 4S\4S jjr0 4S\\	   4S jjr
S\S\	4S jrS rS	0 4S
\S\4S jjr0 4S\S\4S jjrSSS\S\	S\4S jjrS	0 4S\S\S\4S jjrSS	S	0 4S\S\S\S\\   4S jjrSSS\	S\4S jjr0 4S\S\4S jjrSSS\	S\4S jjr0 4S\4S jjrSSS\	4S jjrS	S	S	0 4S\ S\S\4S jjr!S	S	0 4S\S\S\S\\"   4S jjr#S	S	S	0 4S\ S\S\4S jjr$SSS\S\	S\"4S jjr%0 4S jr&0 4S\4S  jjr'0 4S\(4S! jjr)S\(4S" jr*S	S	S	0 4S#\ S\S\S\\+   4S$ jjr,S	S	S	0 4S#\ S\S\S\\+   4S% jjr-S	0 4S#\S&\.S'\S(\ S\+4
S) jjr/SSS*\0S\+4S+ jjr1S,\ 4S- jr20 4S#\S\34S. jjr4SSS*\0S\34S/ jjr5S	0 4S\S0\6S1\7S&\.S2\8S\94S3 jjr:0 4S4\\;   4S5 jjr<S	0 4S\S0\6S1\7S&\.S2\84
S6 jjr=S7 r>S	S	S	0 4S\ S\S\4S8 jjr?S	0 4S9\S\ 4S: jjr@S	0 4S9\S\ 4S; jjrAS	0 4S\ 4S< jjrBS	S	S	0 4S\ S\S\S\\9   4S= jjrCSSS>\S\	S\94S? jjrDS,\ 4S@ jrES1\ 4SA jrFS	0 4S
\S\\G   4SB jjrHSSSC\S\	4SD jjrIS	S	S	0 4S\ S\S\4SE jjrJSSS\	4SF jjrKSG rLSHSI0 S	S	4SJ jrMSK rNS#\OSL\SM\SN\SO\SP\4SQ jrPSRrQU =rR$ )Tbackpack   returnc                 	  > U R                  [        [        U ]  5       0 SS_SS_SS/_SS_S	S
_SS_SS_S0 SS _SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_S S_0 S!S_S"S_S#S_S$S_S%S_S&S_S'S_S(S_S)S_S*S_S+S_S,S_S-S_S.S_S/S_S0S_S1S_E0 S2S_S3S_S4S_S5S_S6S_S7S_S8S_S9S_S:S_S;S_S<S_S=S_S>S_S?S_S@S_SAS_SBS_E0 SCS_SDS_SES_SFS_SGS_SHS_SIS_SJS_SKS_SLS_SMS_SNS_SOS_SPS_SQS_SRS_SSS_E0 STS_SUS_SVS_SWS_SXS_SYS_SZS_S[S_S\S_S]S_S^S_S_S_S`S_SaS_SbS_ScS_SdS_E0 SeS_SfS_SgS_ShS_SiS_SjS_SkS_SlS_SmS_SnS_SoS_SpS_SqS_SrS_SsS_StS_E_SuSvSwSxSySzS{S|S}S~SSSSSSS._SSSSS.SSSS._SS0 SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SSS.E00 SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SSSSSSSS.ESSSSSSSSSSS.
SSS.SS0S.S._SSSSS SSSS SSSSSS.SSSSSSSSSS.SS.SS0SSS S SS.S SSSSSS.SSS S SSSS.S SSS.S.	SS0S S S.S S S.S._SSSS._S[        _S0 SSSS._SSS0_SSS0_SSS0_SSS0_SSS0_SSS0_SSS0_SSS0_SSS0_SSS0_SSS0_SSS0_SSS0_SSS0_SSS0_SSSSS._SSSS.SS0SS0SS0SS0SS0SS0SS0SS0SStS.S.
ESSS SSS0 SS_SS_SS_SS_SS_GS GS_GSGS_GSGS_GSGS_GSGS	_GS
GS_GSGS_GSGS_GSGS_GSGS_GSGS_GSGS_GSGSGSGSGSGSGS.E0 GSS_GS S_GS!S_GS"S_GS#S_GS$GS _GS%GS_GS&GS_GS'GS_GS(GS_GS)GS
_GS*GS_GS+GS_GS,GS_GS-GS_GS.GS_GS/GS_GS0GS1GS2GS3GS4GSGS5.EGS6.	_GS70 _GS80 GS9[
        _GS:[        _GS;[
        _GS<[
        _GS=[
        _GS>[        _GS?[        _GS@[        _GSA[        _GSB[
        _GSC[        _GSD[
        _GSE[
        _GSF[
        _GSG[
        _GSH[        _GSI[
        _0 GSJ[        _GSK[
        _GSL[
        _GSM[
        _GSN[        _GSO[        _GSP[        _GSQ[        _GSR[        _GSS[        _GST[        _GSU[        _GSV[        _GSW[         _GSX[        _GSY[        _E0 GSZ._5      $ ([  Nidr-   nameBackpack	countriesJP	rateLimit2   versionv1	certifiedFproThasCORSspotmarginswapfutureoption	addMargincancelAllOrderscancelAllOrdersAftercancelOrdercancelOrderscancelWithdrawclosePositioncreateConvertTradecreateDepositAddresscreateLimitBuyOrdercreateLimitOrdercreateLimitSellOrdercreateMarketBuyOrdercreateMarketBuyOrderWithCostcreateMarketOrdercreateMarketOrderWithCostcreateMarketSellOrdercreateMarketSellOrderWithCostcreateOrdercreateOrders$createOrderWithTakeProfitAndStopLosscreatePostOnlyOrdercreateReduceOnlyOrdercreateStopLossOrdercreateTakeProfitOrdercreateTrailingAmountOrdercreateTrailingPercentOrdercreateTriggerOrderfetchAccountsfetchAllGreeksfetchBalancefetchCanceledAndClosedOrdersfetchCanceledOrdersfetchClosedOrderfetchClosedOrdersfetchConvertCurrenciesfetchConvertQuotefetchConvertTradefetchConvertTradeHistoryfetchCurrenciesfetchDepositAddressfetchDepositsfetchDepositsWithdrawalsfetchDepositWithdrawFeesfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchGreeksfetchIndexOHLCVfetchLedgerfetchLeveragefetchLeverageTiersfetchMarginAdjustmentHistoryfetchMarginModefetchMarketsfetchMarkOHLCVfetchMyTrades
fetchOHLCVfetchOpenInterestfetchOpenInterestHistoryfetchOpenOrderfetchOpenOrdersfetchOptionfetchOptionChain
fetchOrderfetchOrderBookfetchOrdersfetchOrderTradesfetchPositionfetchPositionHistoryfetchPositionModefetchPositionsfetchPositionsForSymbolfetchPositionsHistoryfetchPremiumIndexOHLCVfetchStatusfetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeefetchTradingFeesfetchTransactionsfetchTransfersfetchVolatilityHistoryfetchWithdrawalsreduceMarginsandboxsetLeverage	setMarginsetMarginModesetPositionModetransferwithdraw
timeframes1m3m5m15m30m1h2h4h6h8h12h1d3d1w1month)r   r   r   1530r   r   r   r   r   r   r   r   r   1MurlszOhttps://github.com/user-attachments/assets/cc04c278-679f-4554-9f72-930dd632b80fzhttps://api.backpack.exchange)publicprivatezhttps://backpack.exchange/zhttps://docs.backpack.exchange/z#https://backpack.exchange/join/ccxt)logoapiwwwdocreferralr   getzapi/v1/assets   zapi/v1/collateralzapi/v1/borrowLend/marketsz!api/v1/borrowLend/markets/historyzapi/v1/marketszapi/v1/marketzapi/v1/tickerzapi/v1/tickerszapi/v1/depthzapi/v1/klineszapi/v1/markPriceszapi/v1/openInterestzapi/v1/fundingRateszapi/v1/statuszapi/v1/pingzapi/v1/timezapi/v1/wallets)zapi/v1/tradeszapi/v1/trades/historyzapi/v1/accountzapi/v1/account/limits/borrowzapi/v1/account/limits/orderz api/v1/account/limits/withdrawalzapi/v1/borrowLend/positionszapi/v1/capitalzapi/v1/capital/collateralzwapi/v1/capital/depositszwapi/v1/capital/deposit/addresswapi/v1/capital/withdrawalsapi/v1/positionzwapi/v1/history/borrowLendzwapi/v1/history/interestz$wapi/v1/history/borrowLend/positionszwapi/v1/history/dustzwapi/v1/history/fillszwapi/v1/history/funding)wapi/v1/history/orderswapi/v1/history/rfqwapi/v1/history/quotewapi/v1/history/settlementwapi/v1/history/strategiesapi/v1/orderapi/v1/orders)
zapi/v1/account/convertDustapi/v1/borrowLendr   r   r   z
api/v1/rfqzapi/v1/rfq/acceptzapi/v1/rfq/refreshzapi/v1/rfq/cancelapi/v1/rfq/quote)r   r   )r   postdeletepatchfeatures)GTCIOCFOKPOGTD)EXPIRE_MAKEREXPIRE_TAKEREXPIRE_BOTHNONE)
marginModetriggerPricetriggerPriceTypetriggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedtrailingleveragemarketBuyByCostmarketBuyRequiresPriceselfTradePreventionicebergmax     )r   limitdaysBack	untilDayssymbolRequired)r   r   triggerr   r   )r   r   r   r   r   r   r   )paginater   )	r   rU   rV   r|   r   r   r   re   r}   extendsdefault)linearinverse)r   r>   r@   rA   requiredCredentials)apiKeysecretprecisionModeoptionsaccountQueryaccountUpdate)GETPATCHr   balanceQuerymaxBorrowQuantitymaxOrderQuantitymaxWithdrawalQuantityborrowLendPositionQueryr   POSTborrowLendExecuteborrowPositionHistoryQueryAllborrowHistoryQueryAlldustHistoryQueryAllcollateralQuerydepositAddressQuerydepositQueryAllfillHistoryQueryAllfundingHistoryQueryAllinterestHistoryQueryAllr   
orderQueryorderExecuteorderCancel)r   r  DELETEorderQueryAllorderCancelAllorderHistoryQueryAllpnlHistoryQueryAllrfqHistoryQueryAllquoteHistoryQueryAllsettlementHistoryQueryAllpositionQueryquoteSubmitstrategyHistoryQueryAllwithdrawalQueryAll)r   r  )
r   r   zwapi/v1/history/pnlr   r   r   r   r   r   r   i   r   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SuiSolanaStoryTronXRP)SEISUISOLSTORYTRC20rC  aptosarbitrum	avalanchebase	berachainbitcoinbitcoincashbsccardanodogecoineclipseequalsmoneyethereumhyperliquidlitecoinoptimismpolygonrD  rE  rF  rG  rH  )seisuisolanastorytronxrp)	instructions
recvWindowbrokerIdcurrencyIdsListForParseMarketbrokertimeDifferenceadjustForTimeDifferencenetworksnetworksByIdcommonCurrencies
exceptionsINVALID_CLIENT_REQUESTINVALID_ORDERACCOUNT_LIQUIDATINGBORROW_LIMITBORROW_REQUIRES_LEND_REDEEM	FORBIDDENINSUFFICIENT_FUNDSINSUFFICIENT_MARGININSUFFICIENT_SUPPLYINVALID_ASSETINVALID_MARKETINVALID_PRICEINVALID_POSITION_IDINVALID_QUANTITYINVALID_RANGEINVALID_SIGNATUREINVALID_SOURCEINVALID_SYMBOLINVALID_TWO_FACTOR_CODE
LEND_LIMITLEND_REQUIRES_BORROW_REPAYMAINTENANCEMAX_LEVERAGE_REACHEDNOT_IMPLEMENTEDORDER_LIMITPOSITION_LIMITPRECONDITION_FAILEDRESOURCE_NOT_FOUNDSERVER_ERRORTIMEOUTTOO_MANY_REQUESTSTRADING_PAUSEDUNAUTHORIZED)exactbroad)deep_extendsuperr-   describer*   r    r$   r"   r#   r!   r   r   r%   r(   r&   r)   r'   )self	__class__s    G/home/james-whalen/.local/lib/python3.13/site-packages/ccxt/backpack.pyr  backpack.describe   s   h > @ _C
*_C
J_C
 $_C
 	_C

 t_C
 _C
 4_C
  fff $f 	f
 %f %f Uf "4f 'f tf f !%f  f %ef 'f  &t!f" #D#f$ '%f& ''f( /)f* $T+f, ,T-f. (/f0 01f2 t3f4 5f6 77f8 &t9f: (;f< &u=f> (?f@ ,UAfB -eCfD %dEfF  GfH !%IfJ KfL /MfN &uOfP #EQfR $USfT )%UfV $UWfX $UYfZ +E[f\ "4]f^ &t_f`  afb +Ecfd +Eeff &tgfh #Difj *4kfl $Umfn uofp "4qfr usft  ufv %ewfx /yfz "5{f| }f~ !$f@  AfB dCfD $TEfF +DGfH !$IfJ "4KfL uMfN #EOfP eQfR !$SfT tUfV #EWfX  YfZ '[f\ $U]f^ !$_f` *5afb (cfd )%eff tgfh tifj kfl Tmfn tofp "5qfr #Esft $Uufv !%wfx )%yfz #D{f| }f~ 5f@ uAfB UCfD  EfF "5GfH EIfJ DKf_C
^ __C
@ i=> 48A	A_C
T  '+Q 4Q <Q	
 )! ( ( )! ' ( ,Q .q .q ( &q  &q!" )!#$ *+12'0(!6 6q ;A	
 6q )! 4Q 3A :1 6q *1 5a 3A ? /  0!" 21#$ 34/0126767())*16 78-.78())*&'-../-.,- )*)*
 )!W.1GU_C
d $&+(,,0,1)-+/6:#'#'#'"&#(( #($)$)+/26,0,0+/$)	0 $)5$: r% ',!%$(%)*/& #'&+!%#'$)*/( ',!%$(%)#'$)*.$ *.$)!%#u>@ y ##
 ##OKe_C
| "$}_C
D	 YE	_C
F	 X!$-!0'X!
 %~'X! 325X! 214X! 769X!" 284#X!( ( 3*)X!. ;>=/X!4 1635X!: +4-;X!@ 002AX!F 648GX!L /01MX!R ,4.SX!X .70YX!^ /81_X!d #+ ."/%eX!p  / ."2& 5/ 3, 3, 5. :3 ( ) 83  4 *4iX!r #15"#+07: K F	
 K 9 = 5 9 J y "= Z = :  
!" Y#$ ! #$# /2!U!!  ! F	!
  ! u! "5! 5! u! ! y! "=! ! "5! !  
!!" w#!$ ! #$# /!sRG	_C
l m_C
n ",j"#\" *:" #J	"
 2:"  !2" )*;" *+<" *+<" $Z" %i" $Z" *:" '
" $Z"  ()<!"" %j#"$ %i%"& .z'"( !*)"* 1*+", "=-". +,=/"0 &1"2 "#43"4 %&75"6 *?7"8 )*>9": #L;"< ~="> ():?"@ %&:A"B #$7C"J M'o_C
 _ _	    c                 j   U R                  U5      n0 n[        S[        U5      5       GH  nX$   nU R                  US5      nU R	                  U5      nU R                  US/ 5      n0 n	[        S[        U5      5       H  n
X   nU R                  US5      nU R                  US5      nU R                  U5      nUUU R                  US5      U R                  U R                  U R                  US5      5      5      S.U R                  US5      S	S.S
.S	U R                  US5      U R                  US5      U R                  US5      S	US.	X'   M     S	nS	nS	nU R                  U	5      (       a  SnSnSnU R                  UUS	SU R                  US5      UUUS	S	S	S.S	S	S.S.U	US.5      X7'   GM     U$ )z
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
r   symboltokens
blockchainminimumWithdrawalmaximumWithdrawalminr   minimumDepositN)r   depositdepositEnabledwithdrawEnabledwithdrawalFee)	r1   networklimitsactiver  r   fee	precisioninfoFcryptodisplayName)r  r   )r1   coder  typer2   r  r  r   r  r  rg  r  )publicGetApiV1Assetsrangelensafe_stringsafe_currency_code	safe_listsafe_string_lowernetwork_id_to_codesafe_numberparse_number	omit_zero	safe_boolis_emptysafe_currency_structure)r  paramsresponseresulticurrecy
currencyIdr  rg  parsedNetworksjr  	networkIdnetworkIdLowerCasenetworkCoder  r  r   s                     r  fetch_currenciesbackpack.fetch_currencies  s    ,,V40 q#h-(AkG))'8<J**:6D~~gx<H#%N1c(m,"+ ,,WlC	%)%;%;G\%R""556HI#* $(#3#3G=P#Q#'#4#4T^^DDTDTU\^qDr5s#t%
 $(#3#3G=M#N#'$	 ##~~g7GH $w8I J++G_E!%#%/+ -2 FGH}}^,, 77 ! ((-@ "$  $# 
  $#!	 ++9 FLM )z r  c                     U R                   S   (       a  U R                  5         U R                  U5      nU R                  U5      $ )z
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
rf  )r   load_time_differencepublicGetApiV1Marketsparse_marketsr  r  r  s      r  fetch_marketsbackpack.fetch_markets`  s>     <<12%%'--f5!!(++r  marketc                 4   U R                  US5      nU R                  US5      nU R                  US5      nU R                  U5      nU R                  U5      nUS-   U-   nU R                  US0 5      nU R                  US0 5      n	U R                  U	S5      n
U R                  U	S5      nU R                  U	S	5      nU R                  US
0 5      nU R                  US5      nU R                  US5      nU R                  US5      nU R	                  U R                  US5      5      nS nS nS nS nS nUS:X  a  SnO9US:X  a3  SnSnSnU R                  US5      nU R                  U5      nUSU-   -  nSnU R                  US5      nU R                  0 SU_SU_SU_SU_SU_SU_SU_SU_SW_SUS:H  _SUS:H  _SUS:H  _SS_S S_S!US":H  _S#US:g  _S$U_US S US S S S UUS%.S S S&.UUS&.UU
S&.S S S&.S'.U R                  U R                  US(5      5      US).E5      $ )*Nr  
baseSymbolquoteSymbol/filterspricemaxPriceminPricetickSizequantitymaxQuantityminQuantitystepSize
marketTyper>   r@   TF:r   orderBookStater1   rL  quotesettlebaseIdquoteIdsettleIdr  r?   rA   rB   r  Opencontractr   )amountr  r  )r   r  r  cost	createdAt)r   takermakercontractSizeexpiryexpiryDatetimestrike
optionTyper  r  createdr  )r  r  	safe_dictr  parse_market_typesafe_market_structure	parse8601)r  r  r1   r  r  rL  r  r  r  priceFilterr  r  pricePrecisionquantityFilterr  r  amountPrecisiontypeOfMarketr   r   r  r  r  r  r  s                            r  parse_marketbackpack.parse_marketn  s$   r fh/!!&,7""6=9&&v.''0e#..B7nnWgr:##K<##K<))+zBR@&&~}E&&~}E**>:F--d.>.>v|.TU 6!DV#DFG''>H,,X6FcFl"FL))&2BC)) 2+
"2+
f2+
 D2+
 U	2+

 f2+
 f2+
 w2+
 2+
 D2+
 DFN2+
 dfn2+
 DFN2+
 e2+
 e2+
 n.2+
  !2+
" f#2+
$ (")'  
 '&
 $#
  $ ~~d&6&6v{&KLc2+
 2 2	r  c                 0    SSS.nU R                  X!U5      $ )Nr>   r@   )SPOTPERPr  )r  r  typess      r  r  backpack.parse_market_type  s$    
 T22r  Nsymbolsc                     U R                  5         0 nU R                  U R                  X25      5      nU R                  U5      nU R	                  USU5      $ )a  

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>`
r  )load_marketspublicGetApiV1Tickersextendparse_tickersfilter_by_array_tickers)r  r  r  requestr  tickerss         r  fetch_tickersbackpack.fetch_tickers(  sS     	--dkk'.JK$$X.++GXwGGr  r  c                     U R                  5         U R                  U5      nSUS   0nU R                  U R                  XB5      5      nU R	                  XS5      $ )a  
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>`
r  r1   )r  r  publicGetApiV1Tickerr  parse_tickerr  r  r  r  r
  r  s         r  fetch_tickerbackpack.fetch_ticker8  sZ     	V$fTl
 ,,T[[-IJ  22r  tickerc           	      $   U R                  US5      nU R                  X25      nU R                  X25      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  US5      n	U R                  US5      n
U R                  US5      nU R                  US	5      nU R                  0 SU_S
S _SS _SU_SU_SS _SS _SS _SS _SS _SU_SU_SU_SS _SU_SU_SS _U	U
S S US.EU5      $ )Nr  
firstPrice	lastPricehighlowvolumequoteVolumepriceChangePercentpriceChange	timestampdatetimebid	bidVolumeask	askVolumevwapopencloselastpreviousClosechange
percentageaverage)
baseVolumer  	markPrice
indexPricer  )r  safe_marketsafe_symbolsafe_ticker)r  r  r  marketIdr  r%  r'  r  r  r,  r  r*  r)  s                r  r  backpack.parse_tickerJ  s   " ##FH5!!(3!!(354/vu-%%fh7
&&v}=%%f.BC
!!&-8 !
f!
!
 !
 D	!

 3!
 4!
 !
 4!
 !
 D!
 D!
 T!
 D!
 T!
 f!
  *!!
" t#!
$ %&-!
. / 	r  r   c                 0   U R                  5         U R                  U5      nSUS   0nU R                  U R                  XS5      5      nU R	                  US5      nU R                  US-  5      nU R                  XaU5      n	U R	                  US5      U	S'   U	$ )a'  
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
r  r1   r  r   lastUpdateIdnonce)r  r  publicGetApiV1Depthr  safe_integerparse_to_intparse_order_book)
r  r  r   r  r  r
  r  microsecondsr  	orderbooks
             r  fetch_order_bookbackpack.fetch_order_book  s     	V$fTl
 ++DKK,HI ((;?%%lT&9:	))(IF	!..xH	'r  r   sincec                    U R                  5         U R                  U5      nU R                  U R                  X"5      nUS   US.nSn	U R	                  USS5      u  pU	b  U R                  U	S-  5      US'   Sn
UcM  Uc  U
nU R                  U5      nU	(       a  U R                  U	S-  5      OU R                  5       nXU-  -
  nXS	'   OU R                  US-  5      US	'   U R                  US
5      nUb&  U R                  U5      US'   U R                  US
5      nU R                  U R                  X5      5      nU R                  XX#U5      $ )ae  
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
r1   )r  intervalNr}   untilr   endTimed   	startTimer  	priceType)r  r  r  r   handle_option_and_paramsr9  parse_timeframeseconds
capitalizeomitpublicGetApiV1Klinesr  parse_ohlcvs)r  r  	timeframer?  r   r  r  rA  r
  rB  defaultLimitdurationrC  rE  r  r  s                   r  fetch_ohlcvbackpack.fetch_ohlcv  sZ    	V$##DOOYJTl 
 55flGT!%!2!254<!@GI=}$++I6H9>d''5DLLNG8#34I#,K #'#4#4UT\#BGK   1#'??5#9GK YYvw/F,,T[[-IJ  9UKKr  c           	          U R                  U R                  US5      5      U R                  US5      U R                  US5      U R                  US5      U R                  US5      U R                  US5      /$ )Nstartr%  r  r  r&  r  )r  r  r  )r  ohlcvr  s      r  parse_ohlcvbackpack.parse_ohlcv  sw    $ NN4++E7;<UF+UF+UE*UG,UH-
 	
r  c                 $   U R                  5         U R                  U5      nUS   (       a  [        U R                  S-   U-   5      eSUS   0nU R	                  U R                  XB5      5      nU R                  US0 5      nU R                  Xc5      $ )a=  
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>`
r>   z3 fetchFundingRate() symbol does not support market r  r1   r   )r  r  r    r1   publicGetApiV1MarkPricesr  r  parse_funding_rate)r  r  r  r  r
  r  datas          r  fetch_funding_ratebackpack.fetch_funding_rate  s     	V$&>TWW'\\_eefffTl
 00W1MN~~h2.&&t44r  c                 ~   U R                  US5      nU R                  X25      nU R                  X25      nU R                  US5      n0 SU_SU_SU R	                  US5      _SU R	                  US5      _SS _SS _SS _S	S _S
U R	                  US
5      _SS _SS _SS _SU_SU R                  U5      _SS _SS _SS _SS0E$ )Nr  nextFundingTimestampr  r-  r.  interestRateestimatedSettlePricer  r  fundingRatefundingTimestampfundingDatetimenextFundingRatenextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimerA  r   )r  r/  r0  r8  r  iso8601)r  r  r  r2  r  r_  s         r  rZ  backpack.parse_funding_rate  sZ    ##Hh7!!(3!!(3#00;QR
H
f
 ))(K@
 $**8\B	

 D
 #D
 
 
 4++HmD
 
 t
 t
 #$8
 "4<<0D#E
 "4
  '!
" &t#
$ %
 	
r  c                 $   U R                  5         U R                  U5      nUS   (       a  [        U R                  S-   U-   5      eSUS   0nU R	                  U R                  XB5      5      nU R                  US0 5      nU R                  Xc5      $ )aM  
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:
r>   z4 fetchOpenInterest() symbol does not support market r  r1   r   )r  r  r    r1   publicGetApiV1OpenInterestr  r  parse_open_interest)r  r  r  r  r
  r  interests          r  fetch_open_interestbackpack.fetch_open_interest  s     	V$&>TWW']]`ffggfTl
 224;;w3OP>>(Ar2''99r  c           	          U R                  US5      nU R                  US5      nU R                  US   S UUU R                  U5      US.U5      $ )Nr  openInterestr  )r  openInterestAmountopenInterestValuer  r  r  )r8  r  safe_open_interestrj  )r  ro  r  r  rs  s        r  rn  backpack.parse_open_interest4  se     %%h<	''.A&&X&"&!-"Y/(
  	r  c           	         Uc  [        U R                  S-   5      eU R                  5         U R                  U5      nSUS   0nUb  [	        US5      US'   U R                  U R                  Xd5      5      n/ n[        S[        U5      5       HT  n	Xy   n
U R                  U
S5      nU R                  U5      nUR                  U
US   U R                  U
S5      UUS	.5        MV     U R                  US
5      nU R                  XS   X#5      $ )a  
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>`
z5 fetchFundingRateHistory() requires a symbol argumentr  r1   r   r   r   intervalEndTimestamprb  )r  r  rb  r  r  r  )r   r1   r  r  r  publicGetApiV1FundingRatesr  r  r  r  r  appendr  sort_byfilter_by_symbol_since_limit)r  r  r?  r   r  r  r
  r  ratesr  rater  r  sorteds                 r  fetch_funding_rate_history#backpack.fetch_funding_rate_historyI  s    >#DGG.e$effV$fTl
 "5$/GG224;;w3OP q#h-(A;D''.DEHx0ILL *#//mD&$ 	 ) e[1009I5XXr  c                 J   U R                  5         U R                  U5      nSUS   0nUb  [        US5      US'   SnU R                  US5      nUb!  U R	                  U R                  Xd5      5      nO U R                  U R                  Xd5      5      nU R                  XuX#5      $ )a  
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>`
r  r1   Nr   r   offset)r  r  r  r8  publicGetApiV1TradesHistoryr  publicGetApiV1Tradesparse_trades)	r  r  r?  r   r  r  r
  r  r  s	            r  fetch_tradesbackpack.fetch_tradesw  s     	V$fTl
 "5$/GG""68477G8TUH00W1MNH  5@@r  c                 n   U R                  5         0 nSnUb  U R                  U5      nUS   US'   Ub  X%S'   Ub  X5S'   U R                  US5      nUb  U R                  US/5      nXuS'   U R	                  US5      nUc  S	US'   U R                  U R                  XT5      5      n	U R                  XX#5      $ )
a  
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>`
Nr1   r  fromr   rB  tofillTypeUser)r  r  r8  rK  r  privateGetWapiV1HistoryFillsr  r  )
r  r  r?  r   r  r
  r  rB  r  r  s
             r  fetch_my_tradesbackpack.fetch_my_trades  s     	[[(F &tGH#FO$G!!&'2YYvy1F!DM##FJ7"(GJ44T[[5QR  5@@r  tradec                    U R                  USS5      nU R                  US5      nU R                  XB5      nU R                  US5      nU R                  US5      nU R                  US5      nU(       a  SOSnU R                  US	5      n	U R	                  U R                  US
5      5      n
S nU R                  US5      nU R                  US5      nUb#  U R                  US5      nU R                  U5      nU R                  U R                  US5      5      nUb  UUS S.nU R                  UUU R                  U5      US   UU	S U
UUUS US.U5      $ )Nr1   tradeIdr  r  r  isMakerr  r  orderIdsider  r  	feeSymbol)r  currencyr  )r  r  r  r  r1   orderr  r  takerOrMakerr  r  r  r  )
safe_string_2r  r/  r  parse_order_sider8  r  r  
safe_traderj  )r  r  r  r1   r2  r  r  r  r  r  r  r  	feeAmountr  r  r  s                   r  parse_tradebackpack.parse_trade  sz   8 tY7##E84!!(3  0!!%4..	2")ww""5)4$$T%5%5eV%DE$$UE2	%%e[9	 ''{;Hx0I++D,<,<UK,PQ	 !%C
 "Y/X&( 
  	r  c                 t    U R                  U5      nU R                  US5      nUR                  5       SSSUS.$ )a1  
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>`
statusN)r  updatedetaurlr  )publicGetApiV1Statusr  lower)r  r  r  r  s       r  fetch_statusbackpack.fetch_status  sG     ,,V4 !!(H5lln
 	
r  c                 f    U R                  U5      nU R                  USU R                  5       5      $ )a/  
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
r   )publicGetApiV1Timer8  millisecondsr  s      r  
fetch_timebackpack.fetch_time  s4     **62   1d.?.?.ABBr  c                 f    U R                  5         U R                  U5      nU R                  U5      $ )aF  
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>`
)r  privateGetApiV1Capitalparse_balancer  s      r  fetch_balancebackpack.fetch_balance!  s1     	..v6!!(++r  c                    [        UR                  5       5      n0 n[        S[        U5      5       H  nX$   nU R	                  U5      nX   nU R                  5       nU R                  US5      n	U R                  US5      n
[        R                  " X5      nU R                  US5      US'   XS'   XU'   M     U R                  U5      $ )Nr   lockedstaked	availablefreeused)
listkeysr  r  r  accountr  r+   
string_addsafe_balance)r  r  balanceKeysr  r  r1   r  balancer  r  r  r  s               r  r  backpack.parse_balance.  s     8==?+q#k*+AB**2.DlGllnG%%gx8F%%gx8F%%f5D"..wDGFO"FO"4L ,   ((r  r  c                    U R                  5         0 nSnUb  U R                  U5      nUb  X%S'   Ub  X5S'   SnU R                  USS5      u  ptUb  XuS'   U R                  U R	                  XT5      5      nU R                  XX#5      $ )a  
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>`
Nr  r   rl   rB  rC  )r  r  rG  privateGetWapiV1CapitalDepositsr  parse_transactions	r  r  r?  r   r  r
  r  rB  r  s	            r  fetch_depositsbackpack.fetch_depositsG  s     	
!}}T*H#FO$G55fowW!&I77G8TU&&x5HHr  c                    U R                  5         0 nSnUb  U R                  U5      nUb  X%S'   Ub  X5S'   SnU R                  USS5      u  ptUb  XuS'   U R                  U R	                  XT5      5      nU R                  XX#5      $ )a~  
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>`
Nr  r   r   rB  r  )r  r  rG  "privateGetWapiV1CapitalWithdrawalsr  r  r  s	            r  fetch_withdrawalsbackpack.fetch_withdrawalse  s     	!}}T*H#FO$G55f>PRYZ!DM::4;;w;WX&&x5HHr  r  addresstagc                 j   U R                  5         U R                  U5      nUS   U R                  U5      US.nUb  XGS'   U R                  U5      u  pU R	                  U5      n
U
c  [        U R                  S-   5      eXS'   U R                  U R                  Xy5      5      nU R                  X5      $ )a  
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>`
r1   )r  r  r  clientIdz( withdraw() requires a network parameterr  )
r  r  number_to_stringhandle_network_code_and_paramsnetwork_code_to_idr    r1   #privatePostWapiV1CapitalWithdrawalsr  parse_transaction)r  r  r  r  r  r  r  r
  r  queryr  r  s               r  r   backpack.withdraw  s     	==&tn--f5

 ?"%J!@@H++K8	TWW'QQRR );;DKK<WX%%h99r  r  c                    U R                  U R                  US5      5      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  Xb5      nU R                  U R                  US5      5      nU R	                  US5      n	U R                  USS5      n
U R                  U
5      nU R                  US	5      nU R                  US
5      nU R                  US5      nU R	                  US5      nU R                  USS5      nS nUb  UUS.n0 SU_SU_SU_SU_SU R                  U5      _SU_SS _SU_SU_SU_SS _SS _SS _SU	_SU_SU_SS _US US.E$ ) Nr  r1   transactionHashr  r  r  sourcer  	toAddressfromAddressplatformMemor  
isInternalF)r  r  r  txidr  r  r  r  	addressToaddressFromr  tagTotagFromr  r  r  r  )internalcommentr  )	parse_transaction_statusr  r  r  r  safe_string_lower_2r  r  rj  )r  transactionr  r  r1   r  coinr  r  r  r  r  r  r  r  feeCostr  r  s                     r  r  backpack.parse_transaction  s   R ..t/?/?X/VWk40->?X6&&t6NN4#3#3K#MN	!!+z:,,[(LQ	)))4$$[+>	&&{MB{N;"";6>>+|UC C
K
"
 D
 	

 Y/
 w
 t
 
 ;
 3
 T
 t
 D
 f
 
  f!
" t#
$ !)
 	
r  r  c           	      <    SSSSSSSSS.nU R                  X!U5      $ )	N	cancelledokdeclinedexpired	initiatedpendingrefunded)r  	confirmedr  r  r  r  r  zinformation requiredr   r  r  statusess      r  r  !backpack.parse_transaction_status  s6    $" $ "$-	
 &99r  c                 ,   U R                  5         SnU R                  U5      u  p2Uc  [        U R                  S-   5      eU R	                  U5      nSU R                  U5      0nU R                  U R                  XR5      5      nU R                  Xd5      $ )a  
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>`
Nzb fetchDepositAddress() requires a network parameter, see https://docs.ccxt.com/#/?id=network-codesr  )	r  r  r   r1   r  r  %privateGetWapiV1CapitalDepositAddressr  parse_deposit_address)r  r  r  r  r  r
  r  s          r  fetch_deposit_addressbackpack.fetch_deposit_address"  s     	"AA&I#DGG  /S  %S  T  T==&$11+>
 ==dkk'>Z[))(==r  c                     U R                  US5      nU R                  US5      nU R                  XB5      nUUS   S US S.$ )Nr  r  r  )r  r  r  r  r  )r  safe_currency)r  depositAddressr  r  r  s        r  r  backpack.parse_deposit_address9  sV     "">9=%%njA
%%j;" (
 	
r  r  r  r  c                     U R                  5         U R                  U5      nU R                  XX4XV5      nU R                  U5      n	U R	                  X5      $ )a  
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>`
)r  r  create_order_requestprivatePostApiV1Orderparse_order)
r  r  r  r  r  r  r  r  orderRequestr  s
             r  create_orderbackpack.create_orderJ  sS    > 	V$00tU[--l;11r  ordersc           	         U R                  5         / n[        S[        U5      5       H  nX   nU R                  US5      nU R                  US5      nU R                  US5      nU R	                  US5      n	U R	                  US5      n
U R                  US0 5      nU R                  X5      nU R                  XgXX5      nUR                  U5        M     U R                  U5      nU R                  U5      $ )a  
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>`
r   r  r  r  r  r  r  )r  r  r  r  r  r  r  r  r{  privatePostApiV1Ordersparse_orders)r  r  r  ordersRequestsr  rawOrderr2  r  r  r  r  orderParamsextendedParamsr  r  s                  r  create_ordersbackpack.create_orderso  s     	q#f+&AyH''(;H##Hf5D##Hf5D%%h9F$$Xw7E..8R@K![[=N44XTSXiL!!,/ ' ..~>  **r  c                 F   U R                  U5      nUS   U R                  U5      U R                  U5      S.nU R                  US5      n	U	S Ln
U
(       a  SOSnUS:X  a(  U R	                  X5      US'   U R                  X5      X'   OXUS:X  aR  U R                  US	S
5      nUb)  U R                  X5      US
'   U R                  US	S
/5      nOU R                  X5      X'   U
(       a&  U R	                  X5      US'   U R                  US5      nU R                  US5      nUb  XS'   U R                  US5      nSnU R                  US:H  SU5      u  pU(       a  SUS'   U R                  US5      nUbf  U R                  US5      nUb  U R	                  UU5      US'   U R                  US5      nUb  U R	                  UU5      US'   U R                  US5      nU R                  US5      nUbf  U R                  US5      nUb  U R	                  UU5      US'   U R                  US5      nUb  U R	                  UU5      US'   U R                  US5      nS nU R                  USS5      u  nnUb#  US:X  a  SUS'   OUS:X  a  SUS'   OUS:X  a  SUS'   U R                  X5      $ )Nr1   )r  r  	orderTyper   triggerQuantityr  r   r  r  r  quoteQuantityclientOrderIdr  FTpostOnly
takeProfittakeProfitTriggerPricetakeProfitLimitPricestopLossstopLossTriggerPricestopLossLimitPricerU   r   r   RejectMakerr   RejectTakerr   
RejectBoth)r  encode_order_siderJ  r  price_to_precisionamount_to_precisionr  cost_to_precisionrK  r8  handle_post_onlyr  rG  r  )r  r  r  r  r  r  r  r  r
  r   isTriggerOrderquantityKeyr  r  r  r  r  r   r  r  r   r   s                         r  r  backpack.create_order_request  s   V$Tl**40.

 ''?%T1+9'z7?#66vEGG#'#;#;F#KG X%%ffoFD+/+A+A&+O(6FO+DE'+'?'?'O$&*&=&=f&SGN#YYv~6F))&/B$"/JYYv7F001A5&Q!%F:^^FL9
!%)%5%5j.%Q"%1484K4KFTj4k01"..z7CO*262I2I&Ra2b./YYv|4F>>&*5#'#3#3Hn#M #/262I2I&Rf2g./ ,,Xw?M(040G0GP]0^,-YYvz2F"&*&C&CFM[p&q#V*"n41>-.$61>-.$51=-.{{7++r  c                 0    SSS.nU R                  X!U5      $ )NBidAsk)buysellr   r  r  sidess      r  r!  backpack.encode_order_side  s$    
 T22r  c                     U R                  5         0 nSnUb  U R                  U5      nUS   US'   U R                  U R                  XT5      5      nU R	                  XvX#5      $ )a  
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>`
Nr1   r  )r  r  privateGetApiV1Ordersr  r  r  r  r?  r   r  r
  r  r  s           r  fetch_open_ordersbackpack.fetch_open_orders  sh     	[[(F &tGH--dkk'.JK  5@@r  r1   c                     U R                  5         Uc  [        U R                  S-   5      eU R                  U5      nUS   US.nU R	                  U R                  XS5      5      nU R                  U5      $ )aO  
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>`
z, fetchOpenOrder() requires a symbol argumentr1   )r  r  )r  r   r1   r  privateGetApiV1Orderr  r  r  r1   r  r  r  r
  r  s          r  fetch_open_orderbackpack.fetch_open_order  su     	>#DGG.\$\]]V$Tl
 ,,T[[-IJ))r  c                     U R                  5         Uc  [        U R                  S-   5      eU R                  U5      nUUS   S.nU R	                  U R                  XS5      5      nU R                  U5      $ )aW  
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>`
) cancelOrder() requires a symbol argumentr1   )r  r  )r  r   r1   r  privateDeleteApiV1Orderr  r  r8  s          r  cancel_orderbackpack.cancel_order  su     	>#DGG.Y$YZZV$Tl
 //G0LM))r  c                     U R                  5         Uc  [        U R                  S-   5      eU R                  U5      nSUS   0nU R	                  U R                  XB5      5      nU R                  XS5      $ )a  
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>`
r<  r  r1   )r  r   r1   r  privateDeleteApiV1Ordersr  r  r  s         r  cancel_all_ordersbackpack.cancel_all_orders  st     	>#DGG.Y$YZZV$fTl
 00W1MN  22r  c                     U R                  5         0 nSnUb  U R                  U5      nUS   US'   Ub  X5S'   U R                  U R                  XT5      5      nU R	                  XvX#5      $ )a"  
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>`
Nr1   r  r   )r  r  privateGetWapiV1HistoryOrdersr  r  r3  s           r  fetch_ordersbackpack.fetch_orders#  sv     	[[(F &tGH$G55dkk'6RS  5@@r  r  c                    U R                  US5      nU R                  U R                  US5      5      nUb  UnU R                  US5      nU R                  US5      nU R                  U R                  US5      U5      nU R	                  US5      nU R                  US5      n	U R                  U R                  US5      5      n
U R                  USS	5      nU R                  US
5      nU R                  US5      nU R                  U R                  US5      5      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  USS5      nU R                  USS5      nU R                  0 SU_SU_SU_SU_SU R                  U5      _SS _SU_SU_SU	_SU_SU_SU
_S
U_SU_SU_SU_SU_US US US S S.EU5      $ )Nr  r1   r  r  r  r   r  r  r  r  executedQuoteQuantityr  r   executedQuantity
reduceOnlyr  r  r  r  r  r  r  r  r  lastTradeTimestampr  r   r   r  )r  r+  filled	remainingr  r  trades)r8  r  r  r0  r  r  r  parse_order_statusr  
safe_orderrj  )r  r  r  r  
timestamp2r1   r  r  r  r   r  r  r  r  r  r   rM  rK  r  r   r   s                        r  r  backpack.parse_order:  s   z %%e[9	^^D$4$4UK$HI
!"IeT*((
;!!$"2"25("CVL%%e[9&&um<$$T%5%5eV%DE##E:7HI  0'>?(()9)9%)JK''~>!!%);<^^E<8
>>%4**52FH^_,,U4JLde  
E 
" 
 ] 
 	 

 Y/ 
 !$ 
 f 
 D 
 ; 
  
 * 
 D 
 U 
 L 
 ] 
  ! 
" f# 
$ 1 
2 3 	r  c                 :    SSSSSSSS.nU R                  X!U5      $ )Nr%  closedcanceledrejected)NewFilled	CancelledExpiredPartiallyFilledTriggerPendingTriggerFailedr   r  s      r  rP  backpack.parse_order_status  s3    #!%$'
 &99r  c                 0    SSS.nU R                  X!U5      $ )Nr,  r-  )r*  r+  r   r.  s      r  r  backpack.parse_order_side  s$    
 T22r  c                     U R                  5         U R                  U5      nU R                  U5      nU R                  U5      (       a  U$ U R	                  U5      nU R                  USUS5      $ )aH  
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>`
r  F)r  privateGetApiV1Positionparse_positionsr  market_symbolsfilter_by_array_positions)r  r  r  r  	positionss        r  fetch_positionsbackpack.fetch_positions  sl     	//7((2	==!!%%g.--i7ERRr  positionc                 f   U R                  US5      nU R                  US5      nU R                  XB5      nUS   nU R                  US5      nU R                  US5      nU R                  US5      nSn	Sn
[        R                  " US5      (       a  S	n
Uc  S n	S n
U R                  US
5      nU R                  US5      nU R                  US5      nU R	                  0 SU_SU_SU_SU R                  U R                  US5      5      _SU R                  U R                  U R                  US5      5      5      _SS _SU	_SU
_SU R                  US5      _SS _SU_SU_SS _S[        R                  " U5      _SS _SS _SS _U R                  US5      S U R                  US5      UUUS S S S S S.E5      $ )N
positionIdr  
entryPricer-  netCostFlong0shortpnlUnrealizedpnlRealizedestLiquidationPricer  r1   r  r  lastUpdateTimestampr   r  	contractsnetExposureQuantityr  r  notionalr   
collateralinitialMarginimfmmf)initialMarginPercentagemaintenanceMarginmaintenanceMarginPercentagerealizedPnlunrealizedPnlliquidationPricer   marginRatior*  r   r   )r  r/  r+   	string_ltsafe_positionr  rj  
string_abs)r  rj  r  r1   r2  r  rm  r-  rn  r   r  r  r  r  s                 r  parse_positionbackpack.parse_position  sR   F h5##Hh7!!(3!%%h=
$$X{;	""8Y7Wc**D?FD((?C&&x?++H6KL!! #
H#
"#
 f#
 (8(8;(OP	#

 T^^D4D4DX{4[%\]#
 "4#
 f#
 D#
 ))(4IJ#
 D#
 *#
 #
 #
 **73#
 #
  $!#
" T##
$ (,'7'7%'H!%+/+;+;He+L&* 0!#9#
  	r  c                     U R                  5         0 nSnUb  U R                  U5      nUS   US'   Ub  X5S'   U R                  U R                  XT5      5      nU R	                  XvX#5      $ )a`  
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>`
Nr1   r  r   )r  r  privateGetWapiV1HistoryFundingr  parse_incomesr3  s           r  fetch_funding_historybackpack.fetch_funding_history>  sv     	[[(F &tGH$G66t{{77ST!!(EAAr  c           	      *   U R                  US5      nU R                  X25      nU R                  US5      nU R                  US5      nU R                  U R                  US5      5      nU R                  US5      nUUS UU R	                  U5      UUUS.$ )Nr  r  userIdry  rb  )r  r  r  r  r  r1   r  r  )r  r0  r  r  rj  )	r  incomer  r2  r  r  r1   r  r  s	            r  parse_incomebackpack.parse_incomeV  s     ##FH5!!(3!!&*5fh/NN4#3#3F<R#ST	6"Y/	
 		
r  c                 B    U R                  5       U R                  S   -
  $ )Nre  )r  r   )r  s    r  r6  backpack.noncer  s       "T\\2B%CCCr  r   r   c                    SU-   nU R                   S   U   n[        U[        5      (       a  UOU R                  U5      n	US:X  Gac  U R	                  5         [        U R                  5       5      n
U R                  U R                  SSS5      nU R                  U R                  S0 5      nU R                  X0 5      nU R                  XS5      nSnUS	:X  a  US
:X  a  U R                  XX5      nO<U R                  U	5      n[        U5      S:  a  US-  nSU-   S-   U-   S-   U
-   S-   U-   nU R                  U R                  5      nU R!                  USS5      nU R#                  U R%                  U5      US5      nU
UU R&                  USS.nUS:w  a  U R)                  U	5      nSUS'   US:X  a(  U R                  U	5      n[        U5      S:w  a  USU-   -  nX-  nXXeS.$ )Nr  r   r   ra  X-Window5000r`  r  r   r  r   &instruction=
timestamp=&window=    ed255191400)zX-Timestampr  z	X-API-KeyzX-SignaturezX-Broker-Idr   zapplication/jsonzContent-Type?)r  methodbodyheaders)r   
isinstancer  keysortcheck_required_credentialsstrr6  r  r   r  r  generate_batch_payload	urlencoder  base64_to_binaryr   array_sliceeddsaencoder   json)r  pathr   r  r  r  r  endpointr  sortedParamstsra  optionInstructionsoptionPathInstructionsinstructionpayloadqueryStringsecretBytesseed	signaturer  s                        r  signbackpack.signu  s   :iis#!+FD!9!9vt||F?S)++-TZZ\"B++DLL,
TZ[J!%nb!Q%)^^4Fb%Q"**+A2NKG'f.>55l
`"nn\:{#a'3&K(;6<{J\Y\^^akknxx//<K##KB7D

4;;w#7yII!&![[(%G yy.*<'U?NN<0E5zQC%K'dOOr  c                    Sn[        S[        U5      5       Hj  nU R                  X0 5      nU R                  U5      nU R	                  U5      n	USU-   S-   U	-   S-   -  nU[        U5      S-
  :X  d  M\  USU-   S-   U-   -  nMl     U$ )Nr  r   r  r  r   r  r  )r  r  r  r  r  )
r  r  r  ra  r  r  r  r  sortedOrderr  s
             r  r  backpack.generate_batch_payload  s    q#f+&ANN6b1E,,u-K4J~3c9JFLLGS[1_%<",z9JFF ' r  reasonr  r  r  r  c
                 N   Uc  g U R                  US5      n
U R                  US5      nU
bz  U R                  S-   U-   nU R                  U R                  S   X5        U R                  U R                  S   X5        U R	                  U R                  S   X5        [        U5      eg )Nr  message r  r  )r  r1   throw_exactly_matched_exceptionrj  throw_broadly_matched_exceptionr   )r  r  r  r  r  r  r  r  requestHeadersrequestBody	errorCoder  feedbacks                r  handle_errorsbackpack.handle_errors  s    
 $$Xv6	""8Y7 ww}t+H001I9_001I7]001I7]))r   )N)S__name__
__module____qualname____firstlineno__r   r  r   r  r   r   r  dictr  r  r   r   r  r  r   r  r  r   r   r=  r  rQ  rV  r   r\  rZ  rp  rn  r   r  r   r  r  r  r  r  r   r  r  r   r  r  floatr   r	   r  r  r
   r  r  r   r   r   r   r  r   r  r  r!  r4  r9  r>  rB  rF  r  rP  r  r   rh  r  r  r  r6  r  r  intr  __static_attributes____classcell__)r  s   @r  r-   r-      sv   `# `D ') _Z _B $& ,$v, ,l4 lF l\
3 04B HW H7 H  02 33 3f 3$34 3 36 3j :>b #s #3 #Y #J 26DW[df 'L# 'Lc 'LQT 'Lkoptku 'LR
 
4 
4 68 5 5K 5*!
6 !
[ !
F 79 :# :*F * 8<$]ajl ,Y ,YC ,YWZ ,Y\ 6:UW A3 As A# A\`af\g A: -1tRV_a  Ac  A  AC  ADA Av A AF #% 
2 !# Cs C $& ,( ,) )2 *.Dt\^ I3 Ic I Icghsct I< -1tRV_a Ic I IC Ifjkvfw I: KOWY :S :% :# :C :^i :>r
x r
; r
h:s : 79 ># >^ >.
h 
R` 
" gksu #23 #2i #2y #2RW #2`c #2z #2J @B +D$6 +4 os{} <,3 <,i <,y <,Z_ <,hk <,|3 /3TXac A A3 Ac A* 7;2 *3 * *, 37r *s *C *, /32 3 3( *.Dt\^ A3 Ac A Acghmcn A.J Jv J JX
: 
:3S 3 26b Sw ST(^ S$Qt QV Qf 37TX\eg BC Bs BRU B0
6 
8D &eBSW %PN	# s  c TX `c  r  r-   N)1ccxt.base.exchanger   ccxt.abstract.backpackr   ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   typingr   ccxt.base.errorsr   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   ccxt.base.decimal_to_precisionr*   ccxt.base.preciser+   r-   r  r  r  <module>r     sw    ( . t  t  t  t  t  t  t  * 0 . ' & . . ) , ) . 1 + 4 %["x ["r  