
    eiq                         d dl Zd dlmZmZmZ d dlmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZ d dlmZ d dlmZ d dlmZ d dlmZ  G d d	ej        j                  ZdS )
    N)
ArrayCacheArrayCacheBySymbolByIdArrayCacheByTimestamp)AnyBoolIntMarketOrder	OrderBookPositionStrStringsTickerTickersTrade)Client)List)ExchangeError)ArgumentsRequiredc            
           e Zd Zdef fdZi dfdZi dfdZdedee         de	fd	Z
i fd
edefdZi fd
edefdZdi fdedefdZdi fdedefdZdefdZd@de	dedefdZdi fdedefdZdi fdedefdZdefdZd@dZdddi fd
edededee         fdZdi fd
ededefdZddi fd eee                  dedefd!Zi fd eee                  defd"Zdefd#Z d@defd$Z!ddi fd
edededee"         fd%Z#i fd
edefd&Z$ddi fdee         dededee"         fd'Z%i fdee         defd(Z&defd)Z'd@d*Z(di fd
edede)fd+Z*di fdee         dede)fd,Z+i fd
edefd-Z,i fdee         defd.Z-defd/Z.d0 Z/d1 Z0d2 Z1dddi fd
e2dededee3         fd3Z4di fd
e2defd4Z5defd5Z6d@d6Z7d@d7Z8d8e2fd9Z9dddi fdedededee:         fd:Z;di fdedee         fd;Z<d< Z=d@d=Z>defd>Z?dede@fd?ZA xZBS )Abackpackreturnc                 "   |                      t          t          |                                           i ddddddddddddd	dd
dddddddddddddddddddddddddddddddddiidi i| j        ddd          S )NwsTwatchBalanceFwatchBidsAskswatchMyTrades
watchOHLCVwatchOHLCVForSymbolswatchOrderBookwatchOrderBookForSymbolswatchOrderswatchPositionswatchTickerwatchTickerswatchTradeswatchTradesForSymbolsunwatchBidsAsksunwatchOHLCVunwatchOHLCVForSymbols)unwatchOrderBookunwatchOrderBookForSymbolsunwatchTickerunwatchTickersunWatchTradesunWatchTradesForSymbolsunWatchOrdersunWatchPositionsapizwss://ws.backpack.exchange)publicprivate
timeframesi )ping	keepAlive)hasurlsoptions	streaming)deep_extendsuperr   describer7   )self	__class__s    O/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/pro/backpack.pyr?   zbackpack.describe   s{   h 5 5 > > @ @d    	
 d ' !$ +D t !$ t  t ( "4  !" )$#$ %).2!%"&!%+/!%$(3  8 ">#?   
 	# Q,C
 ,C
 , , ,	    Fc                    K   |                                   d {V  | j        d         d         d         }|rdnd}||d}|                     ||          }|r|                     |||           d S |                     ||||           d {V S )Nr3   r   r4   UNSUBSCRIBE	SUBSCRIBE)methodparams)load_marketsr:   r=   handle_unsubscriptionswatch_multiple)	r@   topicsmessageHashesrH   unwatchurlrG   requestmessages	            rB   watch_publiczbackpack.watch_public@   s      !!!!!!!!!it$X."):{
 
 ""7F33 	'']GDDD4((mWmTTTTTTTTTrC   c                   K   |                                   | j        d         d         d         }d}t          |                                           }|rdnd}|                     | j        ddd	          }	d
|z   dz   dz   |z   dz   |	z   }
|                     | j                  }|                     |dd          }| 	                    | 
                    |
          |d          }||| j        |||	gd}|                     ||          }|r|                     |||           d S |                     ||||           d {V S )Nr3   r   r5   	subscriberE   rF   
recvWindowzX-Window5000zinstruction=&z
timestamp=z&window=r       ed25519)rG   rH   	signature)check_required_credentialsr:   strnoncesafe_string_2r;   base64_to_binarysecretarray_sliceeddsaencodeapiKeyr=   rJ   rK   )r@   rL   rM   rH   rN   rO   instructiontsrG   rU   payloadsecretBytesseedrZ   rP   rQ   s                   rB   watch_privatezbackpack.watch_privateN   sk     '')))it$Y/!"):{''lJPVWW
 ;.4|CbH:UXbb++DK88Q33JJt{{733T9EE	+y"jA
 

 ""7F33 	'']GDDD4((mWmTTTTTTTTTrC   rO   rM   rQ   c                    |                      |          }|                     ||||           t          dt          |                    D ]}||         }|                    dd          }|                     |||           |                    d          dk    r(|                    dd          }|| j        v r| j        |= y|                    d          dk    r(|                    dd          }|| j        v r| j        |= |                    d          dk    ri|	                    d	          }	| 
                    |	d
          }| 
                    |	d          }
|| j        v r|
| j        |         v r| j        |         |
= <|                    d          dk    r)|                    dd          }|| j        v r| j        |= ~|                    d          dk    r)|                    dd          }|| j        v r| j        |= |                    d          dk    r|dk    rZ| j        }t          |                                          }t          dt          |                    D ]}||         }| j        |= 9|                    dd          }|| j        v r| j        |= b|                    d          dk    r|dk    rZ| j        }t          |                                          }t          dt          |                    D ]}||         }| j        |= |                    dd          }|| j        v r| j        |= d S )Nr   zunsubscribe: tickerunsubscribe:ticker:bidaskunsubscribe:bidask:candles:      	orderbookunsubscribe:orderbook:tradesunsubscribe:trades:ordersunsubscribe:ordersunsubscribe:orders:	positionsunsubscribe:positionsunsubscribe:positions:)clientrK   rangelenreplaceclean_unsubscriptionfindtickersbidsaskssplitsafe_stringohlcvs
orderbooksrw   ry   listkeysr|   )r@   rO   rM   rQ   r   imessageHashsubMessageHashsymbolsplitHashes	timeframecacher   js                 rB   rJ   zbackpack.handle_unsubscriptionsd   s   S!!CGGGq#m,,-- 0	3 0	3A'*K(00DDN%%fnkJJJ))Q..$,,-BBGGT\))V,!!(++q00$,,-BBGGT]**f-!!),,11)//44))+q99 ,,[!<<	T[(( DK$777 K/	:!!+..!33$,,-ErJJT_,,/!!(++q00$,,-BBGGT[((F+!!(++q00"666 KE

--D"1c$ii00 0 0!%a K//0 )001FKKF,, K/!!+..!33"999 NE

--D"1c$ii00 3 3!%a N6223 )001I2NNF// N62a0	3 0	3rC   r   c                    K   |                                   d{V  |                     |          }|d         }d|d         z   }d|z   }|                     |g|g|           d{V S )a  
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://docs.backpack.exchange/#tag/Streams/Public/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>`
        Nr   ticker.idticker:)rI   marketrR   r@   r   rH   r   topicr   s         rB   watch_tickerzbackpack.watch_ticker   s       !!!!!!!!!V$$!-$v-&&wvFFFFFFFFFrC   c                 @   K   |                      |g|           d{V S )a  
        unWatches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://docs.backpack.exchange/#tag/Streams/Public/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>`
        N)un_watch_tickersr@   r   rH   s      rB   un_watch_tickerzbackpack.un_watch_ticker   s2       **F8V<<<<<<<<<rC   Nsymbolsc                   K   |                                   d{V  |                     |dd          }g }g }t          dt          |                    D ]O}||         }|                     |          }|                    d|z              |                    d|z              P|                     |||           d{V  |                     | j        d|          S )  
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list

        https://docs.backpack.exchange/#tag/Streams/Public/Ticker

        :param str[] symbols: 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>`
        NFr   r   r   r   )	rI   market_symbolsr   r   	market_idappendrR   filter_by_arrayr   )r@   r   rH   rM   rL   r   r   marketIds           rB   watch_tickerszbackpack.watch_tickers   s       !!!!!!!!!%%gtU;;q#g,,'' 	0 	0AQZF~~f--H  V!3444MM)h.////v>>>>>>>>>##DL(GDDDrC   c                   K   |                                   d{V  |                     |dd          }g }g }t          dt          |                    D ]O}||         }|                     |          }|                    d|z              |                    d|z              P|                     |||d           d{V S )r   NFr   r   rn   TrI   r   r   r   r   r   rR   r@   r   rH   rL   rM   r   r   r   s           rB   r   zbackpack.un_watch_tickers   s       !!!!!!!!!%%gtU;;q#g,,'' 	A 	AAQZF~~f--HMM)h.///  !6!?@@@@&&v}fdKKKKKKKKKrC   r   c                 ,   |                      |di           }|                     |d          }|                     |          }|                     ||          }|                     ||          }d|z   }|| j        |<   |                    ||           d S )Ndatasr   )	safe_dictr   safe_marketsafe_symbolparse_ws_tickerr   resolve)	r@   r   rQ   rm   r   r   r   parsedTickerr   s	            rB   handle_tickerzbackpack.handle_ticker   s    $ 44##FC00!!(++!!(F33++FF;;$v-+V|[11111rC   rm   r   c                    |                      |d          }|                     |dz            }|                     |d          }|                     ||          }|                     ||          }|                     |d          }|                     |d          }|                     i d|d|d|                     |          d	|                     |d
          d|                     |d          dd dd dd dd dd d|d|d|dd dd dd dd |                     |d          |                     |d          |d|          S )NE  r   cor   	timestampdatetimehighhlowlbid	bidVolumeask	askVolumevwapopencloselastpreviousClosechange
percentageaveragevV)
baseVolumequoteVolumeinfo)safe_integerparse_to_intr   r   r   safe_tickeriso8601safe_number)	r@   rm   r   microsecondsr   r   r   r   r   s	            rB   r   zbackpack.parse_ws_ticker   s    ((55%%lT&9::	##FC00!!(F33!!(F33,,,, !
f!
!
 Y//!
 D$$VS11	!

 4##FC00!
 4!
 !
 4!
 !
 D!
 D!
 T!
 D!
 T!
 d!
  $!!
" t#!
$ **6377++FC88)!
 !
 !
* +  	rC   c                   K   |                                   d{V  |                     |dd          }g }g }t          dt          |                    D ]O}||         }|                     |          }|                    d|z              |                    d|z              P|                     |||           d{V  |                     | j        d|          S )a~  
        watches best bid & ask for symbols

        https://docs.backpack.exchange/#tag/Streams/Public/Book-ticker

        :param str[] symbols: 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>`
        NFr   bookTicker.bidask:r   )	rI   r   r   r   r   r   rR   r   r   r   s           rB   watch_bids_askszbackpack.watch_bids_asks)  s       !!!!!!!!!%%gtU;;q#g,,'' 	5 	5AQZF~~f--HMM-(2333  V!34444v>>>>>>>>>##DM8WEEErC   c                   K   |                                   d{V  |                     |dd          }g }g }t          dt          |                    D ]O}||         }|                     |          }|                    d|z              |                    d|z              P|                     |||d           d{V S )a7  
        unWatches best bid & ask for symbols
        :param str[] symbols: 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>`
        NFr   r   rp   Tr   r   s           rB   un_watch_bids_askszbackpack.un_watch_bids_asks?  s       !!!!!!!!!%%gtU;;q#g,,'' 	A 	AAQZF~~f--HMM-(2333  !6!?@@@@&&v}fdKKKKKKKKKrC   c                 ,   |                      |di           }|                     |d          }|                     |          }|                     ||          }|                     ||          }d|z   }|| j        |<   |                    ||           d S )Nr   r   r   )r   r   r   r   parse_ws_bid_askr   r   )	r@   r   rQ   r   r   r   r   parsedBidAskr   s	            rB   handle_bid_askzbackpack.handle_bid_askQ  s      ~~gvr22##D#..!!(++!!(F33,,T6::$v- ,f|[11111rC   c                    |                      |d          }|                     ||          }|                      |d          }|                     |d          }|                     |dz            }|                      |d          }|                      |d          }|                      |d          }	|                      |d          }
|                     |||                     |          |||	|
|d	|          S )
Nr   r   r   r   aAbB)r   r   r   r   r   r   r   r   )r   r   r   r   r   r   )r@   rm   r   r   r   r   r   r   r   r   r   s              rB   r   zbackpack.parse_ws_bid_askj  s    ##FC00!!(F33!!&(33((55%%lT&9::	vs++$$VS11	vs++$$VS11	"Y//""	!
 	!
 	 	 		rC   1msincelimitc                 d   K   |                      ||gg|||           d{V }||         |         S )a  
        watches historical candlestick data containing the open, high, low, close price, and the volume of a market

        https://docs.backpack.exchange/#tag/Streams/Public/K-Line

        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        N)watch_ohlcv_for_symbols)r@   r   r   r   r   rH   results          rB   watch_ohlcvzbackpack.watch_ohlcv  sL       33fi5H4I5RWY_````````f~i((rC   r   c                 D   K   |                      ||gg|           d{V S )a  
        watches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://docs.backpack.exchange/#tag/Streams/Public/K-Line

        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        N)un_watch_ohlcv_for_symbols)r@   r   r   rH   s       rB   un_watch_ohlcvzbackpack.un_watch_ohlcv  s8       44vy6I5JFSSSSSSSSSrC   symbolsAndTimeframesc                 F  K   t          |          }|dk    st          |d         t                    st          | j        dz             |                                  d{V  g }g }t          dt          |                    D ]}||         }	|                     |	d          }
|                     |
          }|                     |	d          }|                     | j	        ||          }|
                    d|z   dz   |d         z              |
                    d|d	         z   d
z   |z              |                     |||           d{V \  }}}| j        r|                    ||          }|                     |||dd          }|                     |||          S )a  
        watches historical candlestick data containing the open, high, low, close price, and the volume of a market

        https://docs.backpack.exchange/#tag/Streams/Public/K-Line

        :param str[][] symbolsAndTimeframes: array of arrays containing unified symbols and timeframes to fetch OHLCV data for, example [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        r   z_ watchOHLCVForSymbols() requires a an array of symbols and timeframes, like  ['ETH/USDC', '1m']N   kline..r   candles:r   rr   T)r   
isinstancer   r   r   rI   r   r   r   r6   r   rR   
newUpdatesgetLimitfilter_by_since_limitcreate_ohlcv_object)r@   r   r   r   rH   symbolsLengthrL   rM   r   symbolAndTimeframer   r   tfintervalr   r   rq   filtereds                     rB   r   z backpack.watch_ohlcv_for_symbols  s      011AZ0DQ0G%N%N#DG  /P  %P  Q  Q  Q!!!!!!!!!q#23344 	Q 	QA!5a!8''(:A>>H[[**F!!"4a88B''R@@HMM(X-3fTlBCCC  fX.>!>!Dx!OPPPP+/+<+<V]TZ+[+[%[%[%[%[%[%["	7? 	4$$VU33E--gueQMM''	8DDDrC   c                   K   t          |          }|dk    st          |d         t                    st          | j        dz             |                                  d{V  g }g }t          dt          |                    D ]}||         }|                     |d          }|                     |          }	|                     |d          }
|                     | j	        |
|
          }|
                    d|z   dz   |	d         z              |
                    d|	d	         z   d
z   |z              |                     |||d           d{V S )a!  
        unWatches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://docs.backpack.exchange/#tag/Streams/Public/K-Line

        :param str[][] symbolsAndTimeframes: array of arrays containing unified symbols and timeframes to fetch OHLCV data for, example [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        r   za unWatchOHLCVForSymbols() requires a an array of symbols and timeframes, like  ['ETH/USDC', '1m']Nr   r   r   r   zunsubscribe:candles:r   rr   T)r   r   r   r   r   rI   r   r   r   r6   r   rR   )r@   r   rH   r   rL   rM   r   r   r   r   r   r   s               rB   r   z#backpack.un_watch_ohlcv_for_symbols  s      011AZ0DQ0G%N%N#DG  /R  %R  S  S  S!!!!!!!!!q#23344 	] 	]A!5a!8''(:A>>H[[**F!!"4a88B''R@@HMM(X-3fTlBCCC  !7&:J!JS!PS[![\\\\&&v}fdKKKKKKKKKrC   c                    |                      |di           }|                     |d          }|                     |          }|d         }|                     |d          }|                    d          }|                     |d          }	|| j        vr
i | j        |<   |	| j        |         vr;|                     | j        dd          }
t          |
          }|| j        |         |	<   | j        |         |	         }|                     |          }|	                    |           d	|z   d
z   |	z   }|
                    ||	|g|           d S )Nr   r   r   streamr   r   
OHLCVLimitr   r   rr   )r   r   r   r   r   r   r;   r   parse_ws_ohlcvr   r   )r@   r   rQ   r   r   r   r   r  partsr   r   storedohlcvparsedr   s                  rB   handle_ohlcvzbackpack.handle_ohlcv  sQ   ( ~~gvr22##D#..X&&!!!'844S!!$$UA..	$+%%"$DKT[000%%dlL$GGE*511F-3DK	*F#I.$$T**V 6)C/);	51;?????rC   c           	      (   |                      |                     |d                    |                     |d          |                     |d          |                     |d          |                     |d          |                     |d          gS )NTr   r   r   r   r   )	parse8601r   r   )r@   r	  r   s      rB   r  zbackpack.parse_ws_ohlcv
  s    $ NN4++E37788UC((UC((UC((UC((UC((
 	
rC   c                 D   K   |                      |g|||           d{V S )a!  
        watches information on multiple trades made in a market

        https://docs.backpack.exchange/#tag/Streams/Public/Trade

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trade structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        N)watch_trades_for_symbols)r@   r   r   r   rH   s        rB   watch_tradeszbackpack.watch_trades$  s6       22F8UE6RRRRRRRRRrC   c                 @   K   |                      |g|           d{V S )aw  
        unWatches from the stream channel

        https://docs.backpack.exchange/#tag/Streams/Public/Trade

        :param str symbol: unified symbol of the market to fetch trades for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=public-trades>`
        N)un_watch_trades_for_symbolsr   s      rB   un_watch_tradeszbackpack.un_watch_trades2  s2       55vhGGGGGGGGGrC   c                   K   |                                   d{V  |                     |          }t          |          }|dk    rt          | j        dz             g }g }t          dt          |                    D ]O}||         }	|                     |	          }
|                    d|
z              |                    d|	z              P|                     |||           d{V }| j	        rB| 
                    |d          }|                     |d          }|                    ||          }|                     |||dd          }|                     |d          S )	a   
        watches information on multiple trades made in a market

        https://docs.backpack.exchange/#tag/Streams/Public/Trade

        :param str[] symbols: unified symbol of the market to fetch trades for
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trade structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        Nr   z> watchTradesForSymbols() requires a non-empty array of symbolstrade.trades:r   r   T)rI   r   r   r   r   r   r   r   rR   r   
safe_valuer   r   r   sort_by)r@   r   r   r   rH   r   rL   rM   r   r   r   rw   firsttradeSymbolr   s                  rB   r  z!backpack.watch_trades_for_symbols>  s~      !!!!!!!!!%%g..GA#DG.n$noooq#g,,'' 	5 	5AQZF~~f--HMM(X-...  V!34444((GGGGGGGG? 	8OOFA..E**5(;;KOOK77E++FE5+tTT||FK000rC   c                   K   |                                   d{V  |                     |          }t          |          }|dk    rt          | j        dz             g }g }t          dt          |                    D ]O}||         }|                     |          }|                    d|z              |                    d|z              P|                     |||d           d{V S )az  
        unWatches from the stream channel

        https://docs.backpack.exchange/#tag/Streams/Public/Trade

        :param str[] symbols: unified symbol of the market to fetch trades for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=public-trades>`
        Nr   z@ unWatchTradesForSymbols() requires a non-empty array of symbolsr  rx   T)	rI   r   r   r   r   r   r   r   rR   )	r@   r   rH   r   rL   rM   r   r   r   s	            rB   r  z$backpack.un_watch_trades_for_symbols^  s      !!!!!!!!!%%g..GA#DG.p$pqqqq#g,,'' 	A 	AAQZF~~f--HMM(X-...  !6!?@@@@&&v}fdKKKKKKKKKrC   c                    |                      |di           }|                     |d          }|                     |          }|d         }|| j        vr5|                     | j        dd          }t          |          }|| j        |<   | j        |         }	|                     ||          }
|	                    |
           d|z   }|	                    |	|           |	                    |	d           d S )Nr   r   r   tradesLimitr   r  rw   )
r   r   r   rw   r   r;   r   parse_ws_trader   r   )r@   r   rQ   r   r   r   r   r   r  r   trader   s               rB   handle_tradeszbackpack.handle_tradesv  s    $ ~~gvr22##D#..X&&!$+%%%%dlM4HHE&&F"(DKF###D&11U&(uk***uh'''''rC   c                 h   |                      |d          }|                     |dz            }|                     |d          }|                     |d          }|                     ||          }|                     |d          }|rdnd}|rdnd	}	|                     |d
          }
|                     |d          }d }|dk    r|                     |d          }n|                     |d          }|                     ||||                     |          |d         |d ||	|
|d d d dd|          S )Nr   r   tr   msellbuymakertakerpqr   r   r   currencycost)r   r   r   r   r   ordertypesidetakerOrMakerpriceamountr-  fee)r   r   r   r   	safe_bool
safe_trader   )r@   r   r   r   r   r   r   isMakerr0  r1  r2  r3  orderIds                rB   r  zbackpack.parse_ws_trade  sm    ((44%%lT&9::	eS))##E3//!!(F33..,, +vve")6www  ,,!!%--5==&&uc22GG&&uc22G"Y//X&(   
  
" #  	rC   c                 B   K   |                      |g||           d{V S )a4  
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://docs.backpack.exchange/#tag/Streams/Public/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
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/?id=order-book-structure>` indexed by market symbols
        N)watch_order_book_for_symbols)r@   r   r   rH   s       rB   watch_order_bookzbackpack.watch_order_book  s4       66xOOOOOOOOOrC   c                   K   |                                   d{V  |                     |dd          }|                     |          }g }g }t          dt	          |                    D ]D}||         }|                    d|z              ||         }	d|	z   }
|                    |
           E|                     |||           d{V }|                                S )a  

        https://docs.backpack.exchange/#tag/Streams/Public/Depth

        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :param str[] symbols: unified array of symbols
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.method]: either '/market/level2' or '/spotMarket/level2Depth5' or '/spotMarket/level2Depth50' default is '/market/level2'
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/?id=order-book-structure>` indexed by market symbols
        NFr   
orderbook:depth.)rI   r   
market_idsr   r   r   rR   r   )r@   r   r   rH   	marketIdsrM   rL   r   r   r   r   ru   s               rB   r:  z%backpack.watch_order_book_for_symbols  s       !!!!!!!!!%%gtU;;OOG,,	q#g,,'' 	! 	!AQZF  !6777 |Hx'EMM%    ++FM6JJJJJJJJ	   rC   c                 @   K   |                      |g|           d{V S )a  
        unWatches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :param str symbol: unified array of symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/?id=order-book-structure>` indexed by market symbols
        N)un_watch_order_book_for_symbolsr   s      rB   un_watch_order_bookzbackpack.un_watch_order_book  s2       996(FKKKKKKKKKrC   c                   K   |                                   d{V  |                     |dd          }|                     |          }g }g }t          dt	          |                    D ]D}||         }|                    d|z              ||         }d|z   }	|                    |	           E|                     |||d           d{V S )a  
        unWatches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :param str[] symbols: unified array of symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.method]: either '/market/level2' or '/spotMarket/level2Depth5' or '/spotMarket/level2Depth50' default is '/market/level2'
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/?id=order-book-structure>` indexed by market symbols
        NFr   rv   r>  T)rI   r   r?  r   r   r   rR   )
r@   r   rH   r@  rM   rL   r   r   r   r   s
             rB   rB  z(backpack.un_watch_order_book_for_symbols  s       !!!!!!!!!%%gtU;;OOG,,	q#g,,'' 	! 	!AQZF  !9F!BCCC |Hx'EMM%    &&v}fdKKKKKKKKKrC   c                    |                      |di           }|                     |d          }|                     |          }|| j        vr|                                 | j        |<   | j        |         }|                     |d          }|                     |d          }d|z   }	|lt          |j                  }
|                     ddd          }|
|k    r| 	                    | j
        ||	|d i            |j                            |           d S ||k    rd S |                     ||           |                    ||	           d S )	Nr   r   r]   ur=  r    snapshotDelay
   )r   r   r   r   
order_bookr   r   r   handle_optionspawnload_order_bookr   handle_deltar   )r@   r   rQ   r   r   r   storedOrderBookr]   
deltaNoncer   cacheLengthrG  s               rB   handle_order_bookzbackpack.handle_order_book  s[   & ~~gvr22##D#..!!(++$/))&*oo&7&7DOF#/&1!!/7;;&&tS11
"V+=o344K !../?RTUUMm++

4/fdTVWWW!((...FZF/400044444rC   c                    |                      |                     |d          dz            }||d<   |                     |          |d<   |                     |d          |d<   |                     |dg           }|                     |dg           }|d	         }|d
         }|                     ||           |                     ||           d S )Nr  r   r   r   rF  r]   r   r   bidsasks)r   r   r   	safe_listhandle_bid_asks)r@   ru   deltar   rS  rT  
storedBids
storedAskss           rB   rM  zbackpack.handle_delta7  s    %%d&7&7s&C&Cd&JKK	!*	+ $Y 7 7	*!..uc::	'~~eS"--~~eS"--v&
v&
Z...Z.....rC   c                     t          dt          |                    D ]2}|                     ||                   }|                    |           3d S )Nr   )r   r   parse_bid_ask
storeArray)r@   bookSidebidAsksr   bidAsks        rB   rV  zbackpack.handle_bid_asksC  sY    q#g,,'' 	( 	(A''
33F''''	( 	(rC   c                    |                      |d          }|                     |d          }|                     |d          }||dz
  k     rdS t          dt          |                    D ]I}||         }|                     |d          }|                     |d          }	||dz
  k    r
||	k     r|c S Jt          |          S )Nr   r]   Ur   rF  )r   r   r   r   )
r@   ru   r   
firstDeltar]   firstDeltaStartr   rW  
deltaStartdeltaEnds
             rB   get_cache_indexzbackpack.get_cache_indexH  s     ^^E1--
!!)W55++J<<?Q&&&2q#e**%% 	 	A!HE**5#66J((44Ha''eh.>.>5zzrC   c                 R  K   |                                   d{V  d}||                     |          }|d         }d}d}|d|d         z   }d|z   }|                     |g|g|           d{V }| j        r|                    ||          }|                     ||||d          S )	a7  
        watches information on multiple orders made by the user

        https://docs.backpack.exchange/#tag/Streams/Private/Order-update

        :param str [symbol]: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nr   account.orderUpdatery   account.orderUpdate.r   zorders:T)rI   r   rj   r   r   filter_by_symbol_since_limit)	r@   r   r   r   rH   r   r   r   ry   s	            rB   watch_orderszbackpack.watch_ordersX  s       !!!!!!!!![[((FH%F%*VD\9E#f,K))5'K=&IIIIIIII? 	3OOFE22E00tTTTrC   c                    K   |                                   d{V  d}||                     |          }|d         }d}d}|d|d         z   }d|z   }|                     |g|g|d           d{V S )	a  
        unWatches information on multiple orders made by the user

        https://docs.backpack.exchange/#tag/Streams/Private/Order-update

        :param str [symbol]: unified market symbol of the market orders were made in
        :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>`
        Nr   ri  rz   rj  r   r{   T)rI   r   rj   r   s         rB   un_watch_orderszbackpack.un_watch_orderss  s       !!!!!!!!![[((FH%F%**VD\9E/&8K''+MMMMMMMMMrC   c                    d}|                      |di           }|                     |d          }|                     |          }|d         }|                     ||          }| j        }	|	2|                     | j        dd          }
t          |
          }	|	| _        |	                    |           |	                    |	|           |dz   |z   }|	                    |	|           d S )Nry   r   r   r   ordersLimitr   rr   )
r   r   r   parse_ws_orderry   r   r;   r   r   r   )r@   r   rQ   r   r   r   r   r   r
  ry   r   symbolSpecificMessageHashs               rB   handle_orderzbackpack.handle_order  s    2 ~~gvr22##D#..!!(++!$$T622>%%dlM4HHE+E22F DKfv{+++$/#$5$>!v899999rC   c                    |                      |d          }|                      |d          }|                     |d          }|                     |dz            }|                     |                      |d          |          }|                      |d          }|                     ||          }|d         }	|                     |d          }
|                      |d	          }|                     |                      |d
                    }|                      |d          }|                     |d          }|                      |d          }|                      |d          }|                      |d          }d }|                      |d          }||d d}|                     i d|d|d|d| 	                    |          dd d|d|	d|
d|d|d|dd d|dd d|d |d!|d |d |d"|          S )#Nr   r   r   r   Xr   r   r   fSr)  Pr*  Zr   Nr+  r   clientOrderIdr   r   lastTradeTimestampstatusr/  timeInForcer0  r2  	stopPricetriggerPricer   r3  r-  filled)	remainingr4  rw   r   )
r   r   r   parse_ws_order_statusr   safe_string_lowerparse_ws_order_sider   
safe_orderr   )r@   r.  r   r   r{  r   r   r}  r   r   r/  r~  r0  r2  r  r3  r-  r  r4  feeCurrencys                       rB   rq  zbackpack.parse_ws_order  s   6 eS))((44((44%%lT&9::	++D,<,<UC,H,H&QQ##E3//!!(F33!%%eS11&&uc22''(8(8(D(DEE  ,,''s33!!%--s++!!%--&&uc22"' C   
" 
] 
  
 Y//	 

 !$ 
 f 
 f 
 D 
 ; 
 D 
 U 
  
 L 
 t 
 f 
  D! 
" f# 
$ + 
  
  
, -  	rC   c                 D    dddddddd}|                      |||          S )Nr   closedcanceledrejected)NewFilled	CancelledExpiredPartiallyFilledTriggerPendingTriggerFailedr   )r@   r}  r   statusess       rB   r  zbackpack.parse_ws_order_status  s=    #!%$'
 
 &&999rC   r0  c                 :    ddd}|                      |||          S )Nr&  r%  )BidAskr  )r@   r0  sidess      rB   r  zbackpack.parse_ws_order_side  s.    
 
 tT222rC   c                 $  K   |                                   d{V  |                     |          }g }g }|lt          dt          |                    D ]M}||         }|                    d|z              |                    d|                     |          z              Nn*|                    d           |                    d           |                     |||           d{V }	| j        r|	S |                     | j	        |||d          S )a-  
        watch all open positions

        https://docs.backpack.exchange/#tag/Streams/Private/Position-update

        :param str[] [symbols]: list of unified market symbols to watch positions for
        :param int [since]: the earliest time in ms to fetch positions for
        :param int [limit]: the maximum number of positions to retrieve
        :param dict params: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/en/latest/manual.html#position-structure>`
        Nr   z
positions:account.positionUpdate.r|   account.positionUpdateT)
rI   r   r   r   r   r   rj   r   filter_by_symbols_since_limitr|   )
r@   r   r   r   rH   rM   rL   r   r   r|   s
             rB   watch_positionszbackpack.watch_positions  sB      !!!!!!!!!%%g..1c'll++ R R $$%6%?@@@7$..:P:PPQQQQR
   ---MM2333,,V]FKKKKKKKK	? 	11$.'5RWY]^^^rC   c                   K   |                                   d{V  |                     |          }g }g }|lt          dt          |                    D ]M}||         }|                    d|z              |                    d|                     |          z              Nn*|                    d           |                    d           |                     |||d           d{V S )a  
        unWatches from the stream channel

        https://docs.backpack.exchange/#tag/Streams/Private/Position-update

        :param str[] [symbols]: list of unified market symbols to watch positions for
        :param dict params: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/en/latest/manual.html#position-structure>`
        Nr   r~   r  r}   r  T)rI   r   r   r   r   r   rj   )r@   r   rH   rM   rL   r   r   s          rB   un_watch_positionszbackpack.un_watch_positions,  s      !!!!!!!!!%%g..1c'll++ R R $$%BV%KLLL7$..:P:PPQQQQR
   !8999MM2333''vtLLLLLLLLLrC   c                    d}|                      |di           }| j        t                      | _        | j        }|                     |          }|                     |d          }|                     |dz            }||d<   |                     |          |d<   |                    |           |dz   |d         z   }	|                    |g|           |                    |g|	           d S )	Nr|   r   r   r   r   r   rr   r   )	r   r|   r   parse_ws_positionr   r   r   r   r   )
r@   r   rQ   r   r   r   parsedPositionr   r   rr  s
             rB   handle_positionszbackpack.handle_positionsD  s    0 "~~gvr22>!355DN//55((s33%%lT&9::	&/{#%)\\)%<%<z"^$$$$/#$5x8P$P!'555')BCCCCCrC   c                    |                      |d          }|                      |d          }|                     ||          }|d         }|                      |d          }|                      |d          }|                      |d          }|                      |d          }	|                      |d          }
|                      |d	          }|                      |d
          }|                     |d          }d}d}|dk     rd}|d }d }|                     |d          }|                     |dz            }|                     |d          }|                     |d          }|                     i d|d|d|d|dd d|d|d|	d|
dd d|dd d|d |d!|d"|d#|                     |          d |d d |d d d$          S )%Nr   r   r   nr   r   r)  rx  QMr*  Flongr   shortr   r   r$  rv  r   r   notional
marginModeliquidationPrice
entryPricerealizedPnlunrealizedPnlr   	contractscontractSize	markPricer0  hedgedr   r   )maintenanceMarginmaintenanceMarginPercentage
collateralinitialMargininitialMarginPercentageleveragemarginRatio)r   r   r   r   r   safe_positionr   )r@   positionr   r   r   r   r  r  r  r  unrealisedPnlr  r  netQuantityr  r0  r   r   r  r  s                       rB   r  zbackpack.parse_ws_positionk  s   * h,,##Hc22!!(F33!##Hc22++Hc::%%h44
&&x55((377$$Xs33	$$Xs33	&&x55??DFD((377%%lT&9::	&*&6&6x&E&E#"&"2"28S"A"A!! #
H#
"#
 f#
 	#

 $#
  0#
 *#
 ;#
 ]#
 $#
 #
 D#
 #
 D#
 f#
  !#
" Y//##
$ "&+F!'>1#
 #
 #
   	rC   c                    |                      ||          sd S |                     |d          }|                     |d          }|dk    r|                     ||           d S |dk    r|                     ||           d S |dk    r|                     ||           d S |dk    r|                     ||           d S |dk    r|                     ||           d S |dk    s*|d	k    s$|d
k    s|dk    s|dk    s|dk    s|dk    s|dk    r|                     ||           d S |dk    s|dk    s|dk    s|dk    r| 	                    ||           d S d S )Nr   erm   
bookTickerkliner   depthorderAcceptedorderUpdate	orderFillorderCancelledorderExpiredorderModifiedtriggerPlacedtriggerFailedpositionAdjustedpositionOpenedpositionClosedpositionUpdated)
handle_error_messager   r   r   r   r  r!  rQ  rs  r  )r@   r   rQ   r   events        rB   handle_messagezbackpack.handle_message  s!   ((99 	F~~gv..  s++Hvw/////l""00000gfg.....gvw/////g""6733333o%%-)?)?5KCWCW[`dt[t[tx}  BP  yP  yP  TY  ]l  Tl  Tl  pu  yH  pH  pH  LQ  Ud  Ld  Ldfg.....(((E5E,E,ERbIbIbfk  pA  gA  gA!!&'22222 gA  gArC   c                 "   |                      |di           }|                     |d          }	 |0|                     |d          }t          | j        dz   |z             dS # t
          $ r}|                    |           Y d }~nd }~ww xY wdS )NerrorcoderQ    T)r   r   r   r   r   	Exceptionreject)r@   r   rQ   r  r  msgr  s          rB   r  zbackpack.handle_error_message  s     w44  //	&&ui88#DGcMC$78884 	 	 	MM!	ts   2A# #
B-BB)N)C__name__
__module____qualname__r   r?   rR   rj   r\   r   dictrJ   r   r   r   r   r   r   r   r   r   r	   r   r   r   r   r   r   r   r   r   r   r   r  r  r   r  r  r  r  r!  r  r   r;  r:  rC  rB  rQ  rM  rV  rg  r   r
   rl  rn  rs  rq  r  r  r   r  r  r  r  r  r   r  __classcell__)rA   s   @rB   r   r      s       -# - - - - - -^ @B5 U U U U ACE U U U U,33# 33d3i 33RV 33 33 33 33j 68 G G GF G G G G" 9; 
= 
=C 
=s 
= 
= 
= 
= 6:" E E7 E E E E E, 9=R L Lg LC L L L L*2F 2 2 2 26+ +d +F +f + + + +Z 8<B F FW F7 F F F F, ;?r L L Lc L L L L$2V 2 2 2 22       D 8<$]ajl ) ) )C )WZ )quvzq{ ) ) ) )  BFb T T3 T3 TUX T T T T aesw  AC E E$tCy/ EZ] Emp E E E E@ ^` L LT$s)_ Ldg L L L L4%@6 %@ %@ %@ %@N
 
D 
 
 
 
4 <@d[] S S SS S Sbfglbm S S S S 9; 
H 
HC 
Hs 
H 
H 
H 
H OSaenp 1 1d3i 1 1[^ 1uyz  vA 1 1 1 1@ LN L Lc LRU L L L L0(F ( ( ( (B/ / / /b @DB P PS P PS\ P P P P SW_a ! !$s) !C !fo ! ! ! !4 =? L L L3 L L L L PR L LT#Y LVY L L L L*(5 (5 (5 (5 (5T
/ 
/ 
/( ( (
    04$UYbd U U UC Us Uimnsit U U U U6 37r N NC Nc N N N N,':6 ': ': ': ':RH H H HT
: 
: 
: 
:3 3 3 3 3 8<$]ajl _ _W _C _WZ _quv~q _ _ _ _: ;?r M M MdSVi M M M M0%D %D %DNE E E EN3V 3 3 3 3(6 t        rC   r   )ccxt.async_supportccxt ccxt.async_support.base.ws.cacher   r   r   ccxt.base.typesr   r   r   r	   r
   r   r   r   r   r   r   r   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   r   async_supportr    rC   rB   <module>r     s       f f f f f f f f f f t t t t t t t t t t t t t t t t t t t t t t t t t t t t 4 4 4 4 4 4       * * * * * * . . . . . .J J J J Jt!* J J J J JrC   