
    E#iî                       S SK rS SKJrJrJrJr  S SKrS SK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  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\RH                  RJ                  5      r%g)    N)
ArrayCacheArrayCacheBySymbolByIdArrayCacheBySymbolBySideArrayCacheByTimestamp)AnyBalancesBoolIntLiquidationNumOrder	OrderBook	OrderSide	OrderTypePositionStrStringsTickerTickersTrade)Client)List)ExchangeError)AuthenticationError)ArgumentsRequired)
BadRequest)NotSupportedc                     ^  \ rS rSrS\4U 4S jjrS rSSS0 4S\S\4S	 jjrS
 r	S0 4S\
S\S\S\S\4
S jjrSS0 4S\
S\
S\S\S\S\4S jjrS0 4S\
S\4S jjr0 4S\
S\4S jjrS0 4S\S\4S jjrS0 4S\S\4S jjr0 4S\
S\4S jjrS\4S jrS0 4S\S\4S jjrSVS jrSSS0 4S\
S\
S\S\S\\   4
S  jjr SS0 4S!\\\
      S\S\4S" jjr!0 4S!\\\
      S\4S# jjr"S0 4S\
S\
S\4S$ jjr#S\4S% jr$SVS\4S& jjr%S0 4S\
S\S\&4S' jjr'S0 4S\\
   S\S\&4S( jjr(0 4S\\
   S\4S) jjr)0 4S\
S\4S* jjr*S\4S+ jr+S, r,S- r-SS0 4S\
S\S\S\\.   4S. jjr/SS0 4S\\
   S\S\S\\.   4S/ jjr00 4S\\
   S\4S0 jjr10 4S\
S\4S1 jjr2S\4S2 jr3SVS3 jr4S4 r5SSS0 4S\S\S\S\\.   4S5 jjr6S0 4S\S\4S6 jjr7S\4S7 jr8SSS0 4S\S\S\S\\9   4S8 jjr:SVS\S\4S9 jjr;S: r<S; r=S0 4S\S\4S< jjr>SS0 4S\
S\S\S\\?   4S= jjr@S\4S> jrASVS? jrBSSS0 4S\S\S\S\\C   4S@ jjrDS0 4S\S\4SA jjrES\4SB jrFS\4SC jrG0 4S\H4SD jjrIS\4SE jrJSVSF jrK0 4SG jrL0 0 4SH\
SI\
S\SJ\\
   SK\\
   4
SL jjrM0 4SM jrNS\S\O4SN jrPS\4SO jrQS\4SP jrRS\4SQ jrSS\4SR jrTS\4SS jrUS\4ST jrVSUrWU =rX$ )Wbybit   returnc                   > U R                  [        [        U ]  5       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_S#S_S$S_ESSSSS%.ESS&S'S(S)S*.S+S,S-.S+S.S/S0.S1.0SS2S3S4S5S6.S7S8S-.S7S9S:S0.S1.0SS&S'S(S)S*.S;S<S-.S;S=S>S0.S1.0S?.S@SA0SSSB.SC/ SDQ0SESFSGSHSISJSKSLSMSNSOSPSQSRSS.0SESTSUSVSWSXSYSZS[S\S]S^S_S`SS.0Sa.U R                  SbSc.Sd.5      $ )eNwsTcreateOrderWseditOrderWsfetchOpenOrdersWsFfetchOrderWscancelOrderWscancelOrdersWscancelAllOrdersWsfetchTradesWsfetchBalanceWswatchBalancewatchBidsAskswatchLiquidationswatchLiquidationsForSymbolswatchMyLiquidationswatchMyLiquidationsForSymbolswatchMyTrades
watchOHLCVwatchOHLCVForSymbolswatchOrderBookwatchOrderBookForSymbolswatchOrderswatchTickerwatchTickerswatchTradeswatchPositionswatchTradesForSymbolsunWatchTickerunWatchTickersunWatchOHLCVunWatchOHLCVForSymbolsunWatchOrderBookunWatchOrderBookForSymbolsunWatchTrades)unWatchTradesForSymbolsunWatchMyTradesunWatchOrdersunWatchPositionsz&wss://stream.{hostname}/v5/public/spotz)wss://stream.{hostname}/v5/public/inversez(wss://stream.{hostname}/v5/public/optionz(wss://stream.{hostname}/v5/public/linear)spotinverseoptionlinearz"wss://stream.{hostname}/v5/privatez'wss://stream.{hostname}/spot/private/v3)unified
nonUnifiedz4wss://stream.{hostname}/trade/option/usdc/private/v1zwss://stream.bybit.com/v5/trade)rI   contractusdctrade)publicprivatez.wss://stream-testnet.{hostname}/v5/public/spotz1wss://stream-testnet.{hostname}/v5/public/inversez0wss://stream-testnet.{hostname}/v5/public/linearz0wss://stream-testnet.{hostname}/v5/public/option)rI   rJ   rL   rK   z*wss://stream-testnet.{hostname}/v5/privatez/wss://stream-testnet.{hostname}/spot/private/v3z<wss://stream-testnet.{hostname}/trade/option/usdc/private/v1z'wss://stream-testnet.bybit.com/v5/tradez'wss://stream-demo.{hostname}/v5/privatez,wss://stream-demo.{hostname}/spot/private/v3z9wss://stream-demo.{hostname}/trade/option/usdc/private/v1z$wss://stream-demo.bybit.com/v5/trade)apitestdemotradingnametickers)fetchPositionsSnapshotawaitPositionsSnapshotfilterExecTypes)r   AdlTrade	BustTradeSettle
timeframes1m3m5m15m30m1h2h4h6h12h1d1w1M)r`   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   135153060120240360720DWM)r9   r<   r3   rI   rO   iPF  )ping	keepAlive)hasurlsoptions	streaming)deep_extendsuperr   describerz   )self	__class__s    H/home/james-whalen/.local/lib/python3.13/site-packages/ccxt/pro/bybit.pyr   bybit.describe   sP   eT ; ='d'' t' $U	'
 '  ' !%' $U'  ' !%' '  ' $T' .u' &u'  0!'"  #'$ d%'& '''( !$)'* +D+', t-'. t/'0 1'2 t3'4 !$5'6 (7'8  9': !$;'< ='> )$?'@ #DA'B -dC'D  E'F ,0#'!%$(M'T $L'R&P&P	# ,P.W% )M$Z%F$( $T'Z&X&X	# ,X._% )U$b%N$( $L'R&P&P	# ,U.\% )R$_%K$ O:z I  /3.2# & (" !"""$$""""$"""#$ !!!!##"###$!!!#?0d 		"kY@
 Y Y	    c                 |    U R                  U R                  U R                  SS5      S5      nXR                  S'   U$ )N	requestIdr      )sumsafe_integerr~   )r   r   s     r   
request_idbybit.request_id   s7    HHT..t||[!LaP	$-[!r   NFsymbolmethodc                   #    U(       a  SOSnS nS nS nS n	U R                   S   S   n
Ub  U R                  U5      n	U	S   S:H  nU	S   nOJU R                  US U5      u  pU R                  U R                  S5      nU R                  USSU5      nUS:H  nUS	:H  nU(       ac  U R                  5       I S h  vN nU R                  US
S5      nU R                  USS5      nU(       a  U(       d  U(       d  X   S   n
OIX   S   n
OAU(       a  X   S	   n
O2US:X  d  US:X  a  S nU R                  X9US5      u  pX   U   n
OX   S   n
U R                  U
5      n
U
$  N7f)NrS   rR   rT   r#   settleUSDCtypedefaultSettlerI   r   Fr   rP   rO   swapfuturerL   rK   )
r}   markethandle_market_type_and_paramssafe_stringr~   safe_string_2isUnifiedEnabled	safe_boolhandle_sub_type_and_paramsimplode_hostname)r   r   	isPrivater   paramsaccessibilityisUsdcSettledisSpotr   r   urlr   rM   isUnifiedMarginisUnifiedAccountsubTypes                   r   get_url_by_market_typebybit.get_url_by_market_type   s    %.	Hiit$[[(F"8,6M&>D==fdFSLD ,,T\\?KM ..vxR_`M*f4M&. 1133G"nnWa?O#~~gq%@_=M(0(4(0&.dh&6"&"A"A&RXZb"c(1 (2##C(
% 4s   B1E3E4B$Ec                 .    U R                  U/ SQ5      nU$ )N)r   r   r   r   unifiedMargin)omit)r   r   s     r   clean_paramsbybit.clean_params   s    6#bcr   r   sideamountpricec           	        #    U R                  5       I Sh  vN   U R                  XX4XVS5      nU R                  S   S   S   S   nU R                  U5      I Sh  vN   [	        U R                  5       5      n	SU	U/[	        U R                  5       5      [	        U R                  S   5      S	.S
.n
U R                  XXS5      I Sh  vN $  N Nr N7f)a  
create a trade order

https://bybit-exchange.github.io/docs/v5/order/create-order
https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline#createamendcancel-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 fulfilled, in units of the quote currency, ignored in market orders
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.timeInForce]: "GTC", "IOC", "FOK"
:param bool [params.postOnly]: True or False whether the order is post-only
:param bool [params.reduceOnly]: True or False whether the order is reduce-only
:param str [params.positionIdx]: *contracts only*  0 for one-way mode, 1 buy side  of hedged mode, 2 sell side of hedged mode
:param boolean [params.isLeverage]: *unified spot only* False then spot trading True then margin trading
:param str [params.tpslMode]: *contract only* 'full' or 'partial'
:param str [params.mmp]: *option only* market maker protection
:param str [params.triggerDirection]: *contract only* the direction for trigger orders, 'above' or 'below'
:param float [params.triggerPrice]: The price at which a trigger order is triggered at
:param float [params.stopLossPrice]: The price at which a stop loss order is triggered at
:param float [params.takeProfitPrice]: The price at which a take profit order is triggered at
:param dict [params.takeProfit]: *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 dict [params.stopLoss]: *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 str [params.trailingAmount]: the quote amount to trail away from the current market price
:param str [params.trailingTriggerPrice]: the price to trigger a trailing order, default uses the price argument
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
NTrT   r#   rS   rQ   order.create
recvWindowzX-BAPI-TIMESTAMPzX-BAPI-RECV-WINDOWopreqIdargsheader)	load_marketscreate_order_requestr}   authenticatestrr   millisecondsr~   watch)r   r   r   r   r   r   r   orderRequestr   r   requests              r   create_order_wsbybit.create_order_ws   s     @ !!!00tU\`aiit$Y/8$$$)*	  %((9(9(;$<&)$,,|*D&E

 ZZDIII! 	" 	% J5   CCACCA+CCCCCidc           	        #    U R                  5       I Sh  vN   U R                  XX4XVU5      nU R                  S   S   S   S   n	U R                  U	5      I Sh  vN   [	        U R                  5       5      n
SU
U/[	        U R                  5       5      [	        U R                  S   5      S.S	.nU R                  XXS
5      I Sh  vN $  N Nr N7f)a"  
edit a trade order

https://bybit-exchange.github.io/docs/v5/order/amend-order
https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline#createamendcancel-order

:param str id: cancel order id
:param str symbol: unified symbol of the market to create an order in
:param str type: 'market' or 'limit'
:param str side: 'buy' or 'sell'
:param float amount: how much of currency you want to trade in units of base currency
:param float price: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
:param dict [params]: extra parameters specific to the exchange API endpoint
:param float [params.triggerPrice]: The price that a trigger order is triggered at
:param float [params.stopLossPrice]: The price that a stop loss order is triggered at
:param float [params.takeProfitPrice]: The price that a take profit order is triggered at
:param dict [params.takeProfit]: *takeProfit object in params* containing the triggerPrice that the attached take profit order will be triggered
:param float [params.takeProfit.triggerPrice]: take profit trigger price
:param dict [params.stopLoss]: *stopLoss object in params* containing the triggerPrice that the attached stop loss order will be triggered
:param float [params.stopLoss.triggerPrice]: stop loss trigger price
:param str [params.triggerBy]: 'IndexPrice', 'MarkPrice' or 'LastPrice', default is 'LastPrice', required if no initial value for triggerPrice
:param str [params.slTriggerBy]: 'IndexPrice', 'MarkPrice' or 'LastPrice', default is 'LastPrice', required if no initial value for stopLoss
:param str [params.tpTriggerby]: 'IndexPrice', 'MarkPrice' or 'LastPrice', default is 'LastPrice', required if no initial value for takeProfit
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
NrT   r#   rS   rQ   order.amendr   r   r   T)	r   edit_order_requestr}   r   r   r   r   r~   r   )r   r   r   r   r   r   r   r   r   r   r   r   s               r   edit_order_wsbybit.edit_order_ws  s     4 !!!..r4vV\]iit$Y/8$$$)*	 %((9(9(;$<&)$,,|*D&E

 ZZDIII! 	" 	% Jr   c                   #    U R                  5       I Sh  vN   Uc  [        U R                  S-   5      eU R                  XU5      nU R                  S   S   S   S   nU R                  U5      I Sh  vN   [        U R                  5       5      nSU;   a  US	 SUU/[        U R                  5       5      [        U R                  S	   5      S
.S.nU R                  XVXvS5      I Sh  vN $  N N{ N7f)aR  
cancels an open order

https://bybit-exchange.github.io/docs/v5/order/cancel-order
https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline#createamendcancel-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
:param boolean [params.trigger]: *spot only* whether the order is a trigger order
:param str [params.orderFilter]: *spot only* 'Order' or 'StopOrder' or 'tpslOrder'
:returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
Nz+ cancelOrderWs() requires a symbol argumentrT   r#   rS   rQ   orderFilterorder.cancelr   r   r   T)r   r   r   cancel_order_requestr}   r   r   r   r   r~   r   )r   r   r   r   r   r   r   r   s           r   cancel_order_wsbybit.cancel_order_ws?  s      !!!>#DGG.[$[\\00VDiit$Y/8$$$)*	L(]+  %((9(9(;$<&)$,,|*D&E

 ZZDIII) 	"
 	% Js5   C4C.AC44C05A4C4)C2*C40C42C4c                   #    U R                  5       I Sh  vN   U R                  U5      nUS   nSU-   nU R                  USSU5      I Sh  vN nU R                  U5      nU R	                  U R
                  S0 5      nU R                  USS5      nUS   (       d  US:w  a  [        U R                  S	-   5      eUS
US   -   -  nU/nU R                  XT/X5      I Sh  vN $  N N N7f)a  
watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

https://bybit-exchange.github.io/docs/v5/websocket/public/ticker
https://bybit-exchange.github.io/docs/v5/websocket/public/etp-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:Fr9   rW   rX   rI   z> watchTicker() only supports name tickers for contract markets.r   )
r   r   r   r   
safe_valuer~   r   r   r   watch_topics)	r   r   r   r   messageHashr   r~   topictopicss	            r   watch_tickerbybit.watch_tickerc  s      !!!V$!&(//}fUU""6*//$,,rB  &)<f~%9"4TWW'gghhvd|##&&sM6JJJ 	" V Ks4   C*C$6C*C&BC*C( C*&C*(C*symbolsc                   #    U R                  5       I Sh  vN   U R                  USS5      n/ nU R                  US   SSU5      I Sh  vN nU R                  U5      nU R	                  U R
                  S0 5      nU R                  USS5      nU R                  U5      n/ n[        S[        U5      5       H4  n	Xy   n
UR                  US-   U
-   5        UR                  SX   -   5        M6     U R                  XCX5      I Sh  vN nU R                  (       a  0 nXUS	   '   U$ U R                  U R                  S	U5      $  GN- N NB7f)
a   
watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list

https://bybit-exchange.github.io/docs/v5/websocket/public/ticker
https://bybit-exchange.github.io/docs/v5/websocket/public/etp-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:   rW   rX   r   r   r   )r   market_symbolsr   r   r   r~   r   
market_idsrangelenappendr   
newUpdatesfilter_by_arrayrX   )r   r   r   messageHashesr   r~   r   	marketIdsr   imarketIdtickerresults                r   watch_tickersbybit.watch_tickers|  sB     !!!%%gtU;//
E>SYZZ""6*//$,,C  &)<OOG,	q#i.)A |HMM%#+01  WZ!78 * ((VLL??F'-6(#$M##DLL(GDD% 	" [ Ms4   E
E3E

EB:E
E>E
E
E
c           	      8  #    U R                  5       I Sh  vN   U R                  USS5      nU R                  U R                  S0 5      nU R	                  USS5      n/ n/ nU R                  U5      n/ n[        S[        U5      5       HJ  n	Xy   n
X   nUR                  US-   U
-   5        UR                  SU-   5        UR                  S	U-   5        ML     U R                  US   SSU5      I Sh  vN nU R                  US
XXhU5      I Sh  vN $  N N# N7f)a  
unWatches a price ticker

https://bybit-exchange.github.io/docs/v5/websocket/public/ticker
https://bybit-exchange.github.io/docs/v5/websocket/public/etp-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:   rW   rX   r   r   r   zunsubscribe:ticker:r   )r   r   r   r~   r   r   r   r   r   r   un_watch_topics)r   r   r   r~   r   r   subMessageHashesr   r   r   r   r   r   s                r   un_watch_tickersbybit.un_watch_tickers  s      !!!%%gtU;//$,,C  &)<OOG,	q#i.)A |HZFMM%#+01##I$67  !6!?@ * //
E>SYZZ))#xQakqrrr 	" [rs4   DDCD2D3DDDDDc                 x   #    U R                  5       I Sh  vN   U R                  U/U5      I Sh  vN $  N N7f)a  
unWatches a price ticker

https://bybit-exchange.github.io/docs/v5/websocket/public/ticker
https://bybit-exchange.github.io/docs/v5/websocket/public/etp-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)r   r   r   r   r   s      r   un_watch_tickerbybit.un_watch_ticker  s9      !!!**F8V<<< 	"<   :6:8::clientc                    U R                  USS5      nU R                  USS5      nU R                  US0 5      nU R                  US5      S LnU(       a  SOSnS nS n	US:X  a  U R                  U5      n	U	S	   nOUS
:X  a  UR                  S5      n
[	        U
5      nU R                  XS-
  5      nU R                  US S U5      nUS	   nU R                  U R                  U0 5      nU R                  US0 5      nU R                  X5      nU R                  U5      n	U R                  US5      nUU	S'   U R                  U5      U	S'   XR                  U'   SU-   nUR                  U R                  U   U5        g )Nr    r   datausdIndexPricerI   rO   snapshotr   deltar   r   infots	timestampdatetimer   )r   	safe_dictparse_tickersplitr   safe_marketrX   extendr   iso8601resolve)r   r   messager   
updateTyper   r   r   r   parsed
topicPartstopicLengthr   r   r   	rawTickermergedr  r   s                      r   handle_tickerbybit.handle_ticker  s   f   '26%%gvr:
~~gvr2!!$8DvZ*$&&t,FH%F7"S)Jj/K''
!ODH%%hdDAFH%F^^DLL&"=Fvvr:I[[1F&&v.F%%gt4	'{!\\)4z%V&(t||F+[9r   c                 "  #    U R                  5       I Sh  vN   U R                  USS5      n/ nU R                  US   SSU5      I Sh  vN nU R                  U5      nU R	                  U5      n/ n[        S[        U5      5       H3  nXW   nSU-   n	UR                  U	5        UR                  SX   -   5        M5     U R                  XCXb5      I Sh  vN n
U R                  (       a  U
$ U R                  U R                  SU5      $  N N N87f)aU  
watches best bid & ask for symbols

https://bybit-exchange.github.io/docs/v5/websocket/public/orderbook

: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.   zorderbook.1.bidask:r   )r   r   r   r   r   r   r   r   r   r   r   bidsasks)r   r   r   r   r   r   r   r   r   r   r   s              r   watch_bids_asksbybit.watch_bids_asksT  s     !!!%%gtU;//
E?TZ[[""6*OOG,	q#i.)A |H"X-EMM%   WZ!78	 *
 ((VLL??M##DMM8WEE 	" \ Ms4   DD	3D
DB	DD5DDDc                    U R                  US5      nU R                  U R                  US   5      S5      nU R                  U R                  US   5      S5      nU R                  US/ 5      nU R                  US/ 5      nU R	                  US   UU R                  U5      U R                  US5      U R                  US5      U R                  US5      U R                  US5      US.U5      $ )Nr  bidsr   asksr   r   )r   r  r  ask	askVolumebid	bidVolumer   )r   sort_by	aggregate	safe_listsafe_tickerr  safe_number)r   	orderbookr   r  r  r  bestBidbestAsks           r   parse_ws_bid_askbybit.parse_ws_bid_asko  s    %%i=	||DNN9V+<=qA||DNN9V+<=qA..q"-..q"-X&"Y/##GQ/))'15##GQ/))'15	!
 	 		r   r`   	timeframesincelimitc                 `   #    SUS'   U R                  X//X4U5      I Sh  vN nXa   U   $  N7f)a  
watches historical candlestick data containing the open, high, low, and close price, and the volume of a market

https://bybit-exchange.github.io/docs/v5/websocket/public/kline
https://bybit-exchange.github.io/docs/v5/websocket/public/etp-kline

: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
r4   callerMethodNameN)watch_ohlcv_for_symbols)r   r   r)  r*  r+  r   r   s          r   watch_ohlcvbybit.watch_ohlcv  sC      &2!"33f5H4I5Y_``~i(( as   .,.symbolsAndTimeframesc                   #    U R                  5       I Sh  vN   U R                  US5      nU R                  USSSS5      nUS   nU R                  USSU5      I Sh  vN n/ n	/ n
[	        S[        U5      5       H  nX   nU R                  US5      nU R                  U5      nUS   nU R                  US5      nU R                  U R                  X5      nU	R                  SU-   S	-   US
   -   5        U
R                  SU-   S-   U-   5        M     U R                  XX5      I Sh  vN u  nnnU R                  (       a  UR                  UU5      nU R                  UX#SS5      nU R                  UUU5      $  GNf GN! NX7f)a  
watches historical candlestick data containing the open, high, low, and close price, and the volume of a market

https://bybit-exchange.github.io/docs/v5/websocket/public/kline
https://bybit-exchange.github.io/docs/v5/websocket/public/etp-kline

: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 dict: A list of candles ordered, open, high, low, close, volume
Nr   FTr5   r   r   kline.r   r   ohlcv::::)r   get_list_from_object_valuesr   r   r   r   r   r   r_   r   r   r   getLimitfilter_by_since_limitcreate_ohlcv_object)r   r1  r*  r+  r   r   marketSymbolsfirstSymbolr   	rawHashesr   r   r   symbolStringr   unfiedTimeframetimeframeIdr   r)  storedfiltereds                        r   r.  bybit.watch_ohlcv_for_symbols  s     !!!223GK++GT5$M#A&//UDZ\bcc	q#234A'*D++D!4L[[.F!(+L"..tQ7O**4??O]KX3c9F4LHI  \!9D!@?!RS 5 +/*;*;CPY*b$b!	6??OOFE2E--feAtL''	8DD) 	" d %cs6   FE<AFE?C
F)F*AF?FFc           
        #    U R                  5       I Sh  vN   U R                  US5      nU R                  USSSS5      nUS   nU R                  USSU5      I Sh  vN n/ n/ n/ n	[	        S[        U5      5       H  n
X   nU R                  US5      nU R                  U5      nUS   nU R                  US5      nU R                  U R                  X5      nUR                  SU-   S	-   US
   -   5        UR                  SU-   S-   U-   5        U	R                  SU-   S-   U-   5        M     SU0nU R                  USX9XUU5      I Sh  vN $  GN< N N	7f)a8  
unWatches historical candlestick data containing the open, high, low, and close price, and the volume of a market

https://bybit-exchange.github.io/docs/v5/websocket/public/kline
https://bybit-exchange.github.io/docs/v5/websocket/public/etp-kline

: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 dict: A list of candles ordered, open, high, low, close, volume
Nr   FTr5   r   r   r3  r   r   r4  r5  zunsubscribe::ohlcv::r1  ohlcv)r   r6  r   r   r   r   r   r   r_   r   r   )r   r1  r   r   r:  r;  r   r<  r   r   r   r   r=  r   r>  r?  subExtensions                    r   un_watch_ohlcv_for_symbols bybit.un_watch_ohlcv_for_symbols  s     !!!223GK++GT5$M#A&//UDZ\bcc	q#234A'*D++D!4L[[.F!(+L"..tQ7O**4??O]KX3c9F4LHI##I$<t$Co$UV  !7,!F!MP_!_` 5 #$8
 ))#wP`ms  vB  C  C  	C+ 	" d" Cs5   EEAEEC.EEEEEc                 P   #    SUS'   U R                  X//U5      I Sh  vN $  N7f)a  
unWatches historical candlestick data containing the open, high, low, and close price, and the volume of a market

https://bybit-exchange.github.io/docs/v5/websocket/public/kline
https://bybit-exchange.github.io/docs/v5/websocket/public/etp-kline

: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
r4   r-  N)rF  )r   r   r)  r   s       r   un_watch_ohlcvbybit.un_watch_ohlcv  s1      &2!"44v6I5JFSSSSs   &$&c                 R   U R                  US0 5      nU R                  US5      nUR                  S5      n[        U5      nU R                  US5      nU R	                  U5      nU R                  XVS-
  5      n	UR
                  R                  S5      S:  n
U
(       a  SOSnU R                  U	S S U5      nUS   nU R                  U R                  U5      nUc  0 U R                  U'   U R                  X5      c8  U R                  U R                  S	S
5      n[        U5      U R                  U   U'   U R                  U   U   n[        S[        U5      5       H)  nU R                  UU   U5      nUR                  U5        M+     SU-   S-   U-   nXU/nUR                  UU5        g )Nr   r   r   r   rI   rO   r   
OHLCVLimit  r   r4  r5  )r   r   r  r   find_timeframer   findr  ohlcvsr   r~   r   r   parse_ws_ohlcvr   r	  )r   r   r
  r   r   r  r  r?  r)  r   r   
marketTyper   r   ohlcvsByTimeframer+  r@  r   r  r   resolveDatas                        r   handle_ohlcvbybit.handle_ohlcv  s   . w3  '2[[%
*o&&z15''4	##Ja@(2-%V:
!!(D$
C! OODKK@$"$DKK??,8@%%dllL$GE-B5-IDKK	*V$Y/q#d)$A((a&9FMM&! %  &(4/);&1{K0r   c           	          US   (       a  SOSn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      U R                  X5      /$ )	NrJ   turnovervolumestartopenhighlowclose)r   r#  )r   rD  r   volumeIndexs       r   rR  bybit.parse_ws_ohlcv  sz      &,I%6jXeW-UF+UF+UE*UG,U0
 	
r   c                 D   #    U R                  U/X#5      I Sh  vN $  N7f)a
  
watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

https://bybit-exchange.github.io/docs/v5/websocket/public/orderbook

: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+  r   s       r   watch_order_bookbybit.watch_order_book0  s"      66xOOOOs     c                   #    U R                  5       I Sh  vN   [        U5      nUS:X  a  [        U R                  S-   5      eU R	                  U5      nU R                  US   SSU5      I Sh  vN nU R                  U5      nU R                  US   5      nUc  US   (       a  SOSnUS	   (       a  S
nOj/ SQSS
// SQS.nU R                  XvS   S5      nU R                  X(5      (       d3  [        U R                  S-   US   -   S-   U R                  U5      -   5      e/ n	/ n
[        S[        U5      5       HS  nX   nU R                  U5      nS[        U5      -   S-   U-   nU	R                  U5        SU-   nU
R                  U5        MU     U R!                  XZX5      I Sh  vN nUR#                  5       $  GN GNO N7f)a  
watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

https://bybit-exchange.github.io/docs/v5/websocket/public/orderbook

: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
:returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
Nr   zA watchOrderBookForSymbols() requires a non-empty array of symbolsFr6   rI   2     rK   d   )r   rg     rN     )r   rg  rj  rh  rN  )rI   rK   defaultr   rl  z! watchOrderBookForSymbols(): for z markets limit can be one of: 
orderbook.r   
orderbook:)r   r   r   r   r   r   r   r   safe_list_2in_arrayr   jsonr   	market_idr   r   r   r+  )r   r   r+  r   symbolsLengthr   r   limitsselectedLimitsr   r   r   r   r   r   r   r$  s                    r   rc  "bybit.watch_order_book_for_symbols=  s     !!!GA#DGG.q$qrr%%g.//
ECSU[\\""6*WQZ(=!&>BEh +s)2F
 "--fVniPN==77 +N!NQWX^Q_!_  cC  "C  FJ  FO  FO  P^  F_  "_  `  `q#g,'AZF~~f-H 3u:-3h>EMM% &/K  - ( ++COO	  ? 	"
 ]2 Ps5   GF;AG/F>0D6G&G'G>GGc           	        #    U R                  5       I Sh  vN   U R                  USS5      nSnU R                  US5      nUb  U R                  US5      nO"U R	                  US   5      nUS   (       a  SOSnU[        U5      -  n/ n/ n/ n[        S[        U5      5       H^  n	X   n
U R	                  U
5      nUS	   nUS
-   U-   nUR                  SU
-   5        UR                  SU
-   5        UR                  U5        M`     U R                  US   SSU5      I Sh  vN nU R                  USXXhU5      I Sh  vN $  GN+ N$ N	7f)a  
unsubscribe from the orderbook channel

https://bybit-exchange.github.io/docs/v5/websocket/public/orderbook

:param str[] symbols: unified symbol of the market to unwatch the trades for
:param dict [params]: extra parameters specific to the exchange API endpoint
:param int [params.limit]: orderbook limit, default is None
:returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
NFrm  r+  r   rI   rg  rh  r   r   zunsubscribe:orderbook:rn  r6   r$  )r   r   r   r   r   r   r   r   r   r   r   )r   r   r   channelr+  firstMarketr   r   r   r   r   r   r   r   r   s                  r   un_watch_order_book_for_symbols%bybit.un_watch_order_book_for_symbolsi  sY     !!!%%gtU;!!&'2YYvw/F++gaj1K%f-B3E3u:q#g,'AZF[[(Fd|HcMH,E  !9F!BC##L6$9:MM%  ( //
ECSU[\\))#{GTdntuuu- 	"* ]us4   EEDEE E<E=EEEc                 x   #    U R                  5       I Sh  vN   U R                  U/U5      I Sh  vN $  N N7f)a  
unsubscribe from the orderbook channel

https://bybit-exchange.github.io/docs/v5/websocket/public/orderbook

:param str symbol: symbol of the market to unwatch the trades for
:param dict [params]: extra parameters specific to the exchange API endpoint
:param int [params.limit]: orderbook limit, default is None
:returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
N)r   rz  r   s      r   un_watch_order_bookbybit.un_watch_order_book  s9      !!!996(FKKK 	"Kr   c                    U R                  US5      nUR                  S5      S   nUR                  R                  S5      S:  nU R                  US5      nUS:H  nU R	                  US0 5      nU R                  US	5      n	U(       a  SOS
n
U R                  U	S S U
5      nUS   nU R                  US5      nXR                  ;  a  U R                  5       U R                  U'   U R                  U   nXS'   U(       a&  U R                  XUSS5      nUR                  U5        OhU R                  US/ 5      nU R                  US/ 5      nU R                  US   U5        U R                  US   U5        XS'   U R                  U5      US'   SU-   nXR                  U'   UR                  UU5        US:X  aK  U R                  U R                  U   U5      n0 nUUU'   UU R                   U'   UR                  USU-   5        g g )Nr   r   r   rI   r   r   r   r   srO   r   r   bar  r  r  r  rn  rm   r  )r   r  r   rP  r  r  r   
orderbooks
order_bookparse_order_bookresetr!  handle_deltasr  r	  r'  r  )r   r   r
  r   r+  r   r   
isSnapshotr   r   rS  r   r   r  r$  r   r  r  r   bidasknewBidsAskss                        r   handle_order_bookbybit.handle_order_book  s   D   '2C #(A-0j(
~~gvr2##D#.%V:
!!(D$
C!%%gt4	//)&*oo&7DOOF#OOF+	$(,,T9c3OHOOH%>>$R0D>>$R0Dy0$7y0$7%.k"$(LL$;Ij!'&0"+y+.C<**4??6+BFKF "K"(K$*DMM&!NN;	F(:; r   c                 L    U R                  USS5      nUR                  U5        g )Nr   r   )parse_bid_ask
storeArray)r   booksider   bidAsks       r   handle_deltabybit.handle_delta  s$    ##E1a0F#r   c                 d    [        S[        U5      5       H  nU R                  XU   5        M     g )Nr   )r   r   r  )r   r  deltasr   s       r   r  bybit.handle_deltas  s)    q#f+&Ahq	2 'r   c                 F   #    U R                  U/X#U5      I Sh  vN $  N7f)a  
watches information on multiple trades made in a market

https://bybit-exchange.github.io/docs/v5/websocket/public/trade

:param str symbol: unified market symbol of the market trades were made in
: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 list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
N)watch_trades_for_symbols)r   r   r*  r+  r   s        r   watch_tradesbybit.watch_trades  s$      22F8U6RRRRs   !!c                   #    U R                  5       I Sh  vN   U R                  U5      n[        U5      nUS:X  a  [        U R                  S-   5      eU R                  U5      nU R                  US   SSU5      I Sh  vN n/ n/ n[        S[        U5      5       HG  n	X   n
U R                  U
5      nSUS   -   nUR                  U5        SU
-   nUR                  U5        MI     U R                  XhXt5      I Sh  vN nU R                  (       a6  U R                  US5      nU R                  US	5      nUR                  UU5      nU R                  XUS
S5      $  GNH N Nd7f)a  
get the list of most recent trades for a list of symbols

https://bybit-exchange.github.io/docs/v5/websocket/public/trade

:param str[] symbols: 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
:returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
Nr   z> watchTradesForSymbols() requires a non-empty array of symbolsFr;   publicTrade.r   trade:r   r  T)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r7  r8  )r   r   r*  r+  r   rs  r   r   r   r   r   r   r   r   tradesfirsttradeSymbols                    r   r  bybit.watch_trades_for_symbols  s[     !!!%%g.GA#DGG.n$noo""6*//
E=RXYYq#g,'AZF[[(F"VD\1EMM% "V+K  - ( ((VLL??OOFA.E**5(;KOOK7E))&TRR+ 	" Z Ms6   E%EA)E% E!A=E%>E#?A E%!E%#E%c           	        #    U R                  5       I Sh  vN   U R                  USSS5      nU R                  US   SSU5      I Sh  vN n/ n/ n/ n[        S[	        U5      5       H[  nX   nU R                  U5      n	SU	S   -   n
UR                  U
5        SU-   nUR                  U5        UR                  S	U-   5        M]     U R                  US
XXeU5      I Sh  vN $  N N N7f)a-  
unsubscribe from the trades channel

https://bybit-exchange.github.io/docs/v5/websocket/public/trade

:param str[] symbols: unified symbol of the market to unwatch the trades for
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns any: status of the unwatch request
NFTr   rE   r  r   zunsubscribe:trade:r  r  )r   r   r   r   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r   r   s               r   un_watch_trades_for_symbols!bybit.un_watch_trades_for_symbols  s      !!!%%gtUDA//
EC\^deeq#g,'AZF[[(F"VD\1EMM% .7K  -##Hv$56 ( ))#xQakqrrr 	"e ss4   C+C%2C+	C'
BC+ C)!C+'C+)C+c                 x   #    U R                  5       I Sh  vN   U R                  U/U5      I Sh  vN $  N N7f)a*  
unsubscribe from the trades channel

https://bybit-exchange.github.io/docs/v5/websocket/public/trade

:param str symbol: unified symbol of the market to unwatch the trades for
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns any: status of the unwatch request
N)r   r  r   s      r   un_watch_tradesbybit.un_watch_trades2  s9      !!!55vhGGG 	"Gr   c                 v   U R                  US0 5      nU R                  US5      nUnUR                  S5      nUR                  R	                  S5      S:  nU(       a  SOSnU R                  US5      n	U R                  U	S S U5      n
U
S   nU R                  U R                  U5      nUc6  U R                  U R                  S	S
5      n[        U5      nXR                  U'   [        S[        U5      5       H(  nU R                  X^   U
5      nUR                  U5        M*     SU-   nUR                  UU5        g )Nr   r   r   rI   r   rO   r   r   tradesLimitrN  r  )r   r   r  r   rP  r  r  r   r~   r   r   r   parse_ws_trader   r	  )r   r   r
  r   r   r  partsr   rS  r   r   r   r@  r+  jr  r   s                    r   handle_tradesbybit.handle_trades?  s#   ( w3  '2C (A- &VZ
##E1-!!(D$
C!f5>%%dllM4HE&F"(KKq#f+&A((F;FMM&! ' $f,v{+r   c                    U R                  U/ SQ5      nSU;   nU(       a  SOSnUb  US   nU R                  US5      nU R                  XbS U5      nUS   nU R                  USS	5      nU R	                  US
5      n	S n
U R                  US5      nU	c  U(       a  SOSn	OUn
U R                  US5      nU R                  USS5      nU R                  US5      nU R                  UUUU R                  U5      UUS U	U
UUS S S.U5      $ )N)r   TvBTrO   rI   r   r  r   tr  Smbuysellpqr  o)r   r   r  r  r   orderr   r   takerOrMakerr   r   costfee)	safe_string_nr   r  safe_integer_2safe_string_lowerr   r   
safe_trader  )r   rQ   r   r   
isContractrS  r   r   r  r   r  r  r   r   orderIds                  r   r  bybit.parse_ws_tradeg  s;   @ 7em
#-Z6
J##E3/!!(D*E!''sC8	%%eS1OOE3'<56D L  ,##E34""5#."Y/( 
  	r   c                 \    UR                  S5      S:  a  gUR                  S5      S:  a  gg)NrI   r   z
v5/privaterM   rP   )rP  )r   r   s     r   get_private_typebybit.get_private_type  s-    88Fq XXl#q(r   c                 $  #    SnSnU R                  5       I Sh  vN   Ub  U R                  U5      nUSU-   -  nU R                  USXT5      I Sh  vN nU R                  U5      I Sh  vN   SSSS	.nU R	                  XR                  U5      5      n	S
n
U R                  USSS
5      u  pU
(       a  Sn	U R                  Xv/U	/U5      I Sh  vN nU R                  (       a  UR                  X5      nU R                  XX#S5      $  N N N N?7f)a  
watches information on multiple trades made by the user

https://bybit-exchange.github.io/docs/v5/websocket/private/execution
https://bybit-exchange.github.io/docs/v5/websocket/private/fast-execution

: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
:param boolean [params.unifiedMargin]: use unified margin account
:param boolean [params.executionFast]: use fast execution
:returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
r3   myTradesN:T
ticketInfo	executionuser.openapi.perp.traderI   rM   rP   FexecutionFastexecution.fast)r   r   r   r   r   r  handle_option_and_paramsr   r   r7  filter_by_symbol_since_limit)r   r   r*  r+  r   r   r   r   topicByMarketr   r  r  s               r   watch_my_tradesbybit.watch_my_trades  s     ! !!![[(F3<'K//fMM$$$ "-

 /D/DS/IJ $ = =foWfhm n$E((meWfMM??OOF2E00tTT' 	" N$ NsF   DD6DD
D*D+A#DD:D
DDDc           	        #    SnSnSnU R                  5       I Sh  vN   Ub  [        U R                  S-   5      eU R                  USX25      I Sh  vN nU R	                  U5      I Sh  vN   SSS	S
.nU R                  XpR                  U5      5      nSn	U R                  USSS5      u  pU	(       a  SnU R                  US/ U/U/U/U5      I Sh  vN $  N N Nq N
7f)a<  
unWatches information on multiple trades made by the user

https://bybit-exchange.github.io/docs/v5/websocket/private/execution
https://bybit-exchange.github.io/docs/v5/websocket/private/fast-execution

:param str symbol: unified market symbol of the market orders were made in
:param dict [params]: extra parameters specific to the exchange API endpoint
:param boolean [params.unifiedMargin]: use unified margin account
:param boolean [params.executionFast]: use fast execution
:returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
r3   zunsubscribe:myTradesr  NzV unWatchMyTrades() does not support a symbol parameter, you must unwatch all my tradesTr  r  r  r  Fr  r  )	r   r   r   r   r   r   r  r  r   )
r   r   r   r   r   subHashr   r  r   r  s
             r   un_watch_my_tradesbybit.un_watch_my_trades  s
     !,!!!tww  *B   B  C  C//fMM$$$ "-

 /D/DS/IJ $ = =foWfhm n$E))#z2}wiZ_Y`bhiii 	" N$ jsF   C!C5C!CC!+C,A(C!CC!C!C!C!c                 p   U R                  US5      nUS:H  nUS:H  nU R                  US/ 5      n[        U[        5      (       d  U R                  US/ 5      nU R                  c-  U R                  U R                  SS5      n[        U5      U l        U R                  n0 n	U R                  SS	/ 5      n
[        S
[        U5      5       H  nXk   nS nU(       a  U(       d  U R                  U5      nOEU R                  USS5      nU(       a  SnU R                  X5      (       d  M]  U R                  U5      nUS   nSX'   UR                  U5        M     [        U	R                  5       5      n[        S
[        U5      5       H  nSUU   -   nUR!                  UU5        M     SnUR!                  UU5        g )Nr   r  r  r   r   r  rN  r3   r[   r   execTyper   r   r   Tz	myTrades:r  )r   r   
isinstancelistr  r   r~   r   handle_optionr   r   r  rp  parse_trader   keysr	  )r   r   r
  r   rI   r  r   r+  r  r   r[   r   rawTrader  r  r   r  currentMessageHashr   s                      r   handle_my_tradesbybit.handle_my_trades  s   j   '2$!11w3$%%??426D== %%dllM4HE259DM,,_>OQSTq#d)$AwHFM,,X6  ++Hj"E &H}}X??))(3H%F"GOMM&! %  GLLN#q#d)$A!,tAw!6NN6#56 % !v{+r   c                   #    U R                  5       I Sh  vN   SnSnU R                  U5      (       d%  U R                  U5      nSSR                  U5      -   nU R	                  US5      nU R                  USXT5      I Sh  vN nSU-   nU R                  U5      n	U R                  U5      I Sh  vN   U R                  X5        U R                  n
U R                  SS	S5      nU R                  SS
S5      nU(       a6  U(       a/  U
c,  U	R                  S	5      I Sh  vN nU R                  XX#S5      $ S/nU R                  X/X5      I Sh  vN nU R                  (       a  U$ U R                  XX#S5      $  GNd N N Nb N37f)a  

https://bybit-exchange.github.io/docs/v5/websocket/private/position

watch all open positions
:param str[] [symbols]: list of unified market symbols
: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<   r   r5  ,r   T	positionsrY   rZ   position)r   is_emptyr   joinr   r   r   r   set_positions_cacher  r  r   filter_by_symbols_since_limitr   r   )r   r   r*  r+  r   r   r   r;  r   r   cacherY   rZ   r   r   newPositionss                   r   watch_positionsbybit.watch_positionss  s     !!!!}}W%%))'2G'!22K&&w2//T6RR!K/S!$$$  1!%!3!34DF^`d!e!%!3!34DF^`d!e!&<#]]+CDDH55hW[\\!..sM6RR??11%%PTUU- 	" S 	% E SsY   FE:A+FE=.F1E?2A,FF0FF+F=F?FFFc                     U R                   b  g U R                  SSS5      nU(       a@  SnXAR                  ;  a.  UR                  U5        U R	                  U R
                  X5        g g [        5       U l         g )Nr<   rY   T)r  r  futuresr   spawnload_positions_snapshotr   )r   r   r   rY   r   s        r   r  bybit.set_positions_cache  sj    >>%!%!3!34DF^`d!e!2K>>1k*

477M 2 67DNr   c                   #    U R                  S SSS.5      U R                  S SSS.5      /n[        R                  " U6 I S h  vN n[        5       U l        U R                  n[        S[        U5      5       H8  nXF   n[        S[        U5      5       H  nXx   n	UR                  U	5        M     M:     UR                  U   n
U
R                  U5        UR                  US5        g  N7f)Nr   rL   )r   r   rJ   r   r  )
fetch_positionsasynciogatherr   r  r   r   r   r  r	  )r   r   r   fetchFunctionspromisesr  r   r  iir  r   s              r   r  bybit.load_positions_snapshot  s        8'LM  9'MN
 !8813q#h-(A IAs9~.$=X& / ) ,uuj) 9s   AC)C'B$C)c                    U R                   c  [        5       U l         U R                   n/ nU R                  US/ 5      n[        S[	        U5      5       H  nXV   nU R                  U5      nU R                  US5      n	UR                  U5        U	b  U	S:X  a3  SUS'   UR                  U5        SUS'   UR                  U5        S US'   Mw  UR                  U5        M     U R                  US5      n
[        S[	        U
5      5       Hk  nX   nUR                  S5      nUS	   nUR                  S
5      nU R                  USUS5      nU R                  U5      (       a  MZ  UR                  X5        Mm     UR                  US5        g )Nr   r   r   r   longshortzpositions::r5  r   r  r   Fr  )r  r   r   r   r   parse_positionr   r   find_message_hashesr  r   r  r	  )r   r   r
  r  r  rawPositionsr   rawPositionr  r   r   r   r  symbolsStringr   r  s                   r   handle_positionsbybit.handle_positions  su   P >>!57DNw;q#l+,A&/K**;7H##Hf5D )|trz $* X&#* X&#'  X&# -$ 00Gq#m,-A'*K%%d+E!!HM#))#.G,,\8WeTI==++y6 . 	|[1r   c           	      ^  #    U R                  5       I Sh  vN   SnSnSnU R                  U5      (       d  [        U R                  S-   5      eU R	                  SSX25      I Sh  vN nU R                  U5      I Sh  vN   S/nU R                  USX/U/Xr5      I Sh  vN $  N NA N* N
7f)a  
unWatches all open positions

https://bybit-exchange.github.io/docs/v5/websocket/private/position

:param str[] [symbols]: list of unified market symbols
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: status of the unwatch request
Nr<   zunsubscribe:positionsr  zT unWatchPositions() does not support a symbol parameter, you must unwatch all ordersTr  )r   r  r   r   r   r   r   )r   r   r   r   r   r  r   r   s           r   un_watch_positionsbybit.un_watch_positions   s      !!!!-}}W%%tww)  A  A//dFKK$$$))#{G]U\T]_ennn 	" L$nsF   B-B%AB-%B'&B->B)?!B- B+!B-'B-)B-+B-c                   #    U R                  5       I Sh  vN   U R                  U5      nUS   nU R                  USSU5      I Sh  vN nU R                  U5      nSnU R	                  USSS5      u  ptSU-   nUS-   US	   -   n	U R                  Xh/U	/U5      I Sh  vN n
U R                  (       a  U
$ U R                  U R                  U/X#S
5      $  N N N:7f)a[  
watch the public liquidations of a trading pair

https://bybit-exchange.github.io/docs/v5/websocket/public/liquidation

:param str symbol: unified CCXT market symbol
:param int [since]: the earliest time in ms to fetch liquidations for
:param int [limit]: the maximum number of liquidation structures to retrieve
:param dict [params]: exchange specific parameters for the bitmex api endpoint
:param str [params.method]: exchange specific method, supported: liquidation, allLiquidation
:returns dict: an array of `liquidation structures <https://github.com/ccxt/ccxt/wiki/Manual#liquidation-structure>`
Nr   Fr/   r   liquidationliquidations::r   r   T)	r   r   r   r   r  r   r   r  liquidations)r   r   r*  r+  r   r   r   r   r   r   newLiquidations              r   watch_liquidationsbybit.watch_liquidations  s      !!!V$!//?RTZ[[""6*66v?RT\^kl&/vd|+#00meWfUU??!!11$2C2CfXu]abb 	" \ Vs4   CC1CC	ACC7CCCc                    [        US   [        5      (       a  U R                  US/ 5      n[        S[	        U5      5       H  nX4   nU R                  US5      nU R                  US SS5      nUS   nU R                  XW5      n	U R                  U R                  U5      n
U
c(  U R                  U R                  SS5      n[        U5      n
U
R                  U	5        XR                  U'   UR                  U	/S	5        UR                  U	/S
U-   5        M     g U R                  US0 5      nU R                  US5      nU R                  US SS5      nUS   nU R                  XW5      n	U R                  U R                  U5      n
U
c(  U R                  U R                  SS5      n[        U5      n
U
R                  U	5        XR                  U'   UR                  U	/S	5        UR                  U	/S
U-   5        g )Nr   r   r  r   rO   r   liquidationsLimitrN  r  r  )r  r  r!  r   r   r   r  parse_ws_liquidationr   r  r   r~   r   r   r	  r  )r   r   r
  rawLiquidationsr   rawLiquidationr   r   r   r  r  r+  s               r   handle_liquidationbybit.handle_liquidation0  s   < gfot,,"nnWfbAO1c/23!0!3++NC@))(D"jI)"77O#t/@/@&I' --dll<OQUVE#-e#4L##K0,8!!&)}n=}.>.GH 4 "^^GVR@N''AH%%hb*EFH%F33NKK??4+<+<fEL#))$,,8KTR)%0,(4f%NNK=.9NNK=*:V*CDr   c                 V   U R                  USS5      nU R                  X2SS5      nU R                  USS5      nU R                  UUS   U R	                  USS5      U R                  US	5      U R	                  US
S5      U R                  USS5      S S UU R                  U5      S.
5      $ )Nr   r  r   rO   updatedTimer  sizer  contractSizer   r  r   r  )
r   r   	contractsr  r   r   	baseValue
quoteValuer  r  )r   r  r  safe_liquidationsafe_number_2r#  r  r  )r   r  r   r   r  s        r   r  bybit.parse_ws_liquidationm  s    $ %%k8SA!!(B
C'']CH	$$X&++KE ,,V^D''WcB**;D"Y/&
  	r   c                   #    U R                  5       I Sh  vN   SnSnUb  U R                  U5      nUSU-   -  nU R                  USXT5      I Sh  vN nU R                  U5      I Sh  vN   SS/S/S/S	.nU R	                  XR                  U5      5      n	U R                  Xv/X5      I Sh  vN n
U R                  (       a  U
R                  X5      nU R                  XX#S5      $  N N N N?7f)
a  
watches information on multiple orders made by the user

https://bybit-exchange.github.io/docs/v5/websocket/private/order

: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>`
Nr8   ordersr  Tr  	stopOrderuser.openapi.perp.orderr  )
r   r   r   r   r   r  r   r   r7  r  )r   r   r*  r+  r   r   r   r   topicsByMarketr   r%  s              r   watch_ordersbybit.watch_orders  s      !!![[(F3<'K//fMM$$$k*y./ 

 1F1Fs1KL((mVLL??OOF2E00tTT# 	" N$ MsF   C1C):C1C+C1*C-+AC1/C/0:C1+C1-C1/C1c           	        #    U R                  5       I Sh  vN   SnSnSnUb  [        U R                  S-   5      eU R                  USX25      I Sh  vN nU R	                  U5      I Sh  vN   SS/S/S	/S
.nU R                  XpR                  U5      5      nU R                  US/ U/U/X5      I Sh  vN $  N Ni NR N
7f)a  
unWatches information on multiple orders made by the user

https://bybit-exchange.github.io/docs/v5/websocket/private/order

:param str symbol: unified market symbol of the market orders were made in
:param dict [params]: extra parameters specific to the exchange API endpoint
:param boolean [params.unifiedMargin]: use unified margin account
:returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
Nr8   zunsubscribe:ordersr%  zQ unWatchOrders() does not support a symbol parameter, you must unwatch all ordersTr  r&  r'  r  )r   r   r   r   r   r   r  r   )	r   r   r   r   r   r  r   r(  r   s	            r   un_watch_ordersbybit.un_watch_orders  s      !!!*tww)||}}//fMM$$$k*y./ 

 1F1Fs1KL))#xk]WIW]fff 	" N$ gsF   CB:;CB<C+B>,A	C5C 6C<C>C Cc                     U R                  US5      nU R                  US5      nU R                  U5      nUR                  XS5        g )Nr   r   )r   r  parse_orderr	  )r   r   r
  r   r   r  s         r   handle_order_wsbybit.handle_order_ws  sB    * &&w8~~gv.  &u*r   c                    U R                   c-  U R                  U R                  SS5      n[        U5      U l         U R                   nU R	                  US/ 5      nU R	                  US0 5      nU R                  US5      nUS:H  nU(       d  U R	                  USU5      n0 n	[        S[        U5      5       H0  n
U R                  XZ   5      nUS   nS	X'   UR                  U5        M2     [        U	R                  5       5      n[        S[        U5      5       H  n
S
X   -   nUR                  XN5        M     SnUR                  XO5        g )NordersLimitrN  r   r   categoryrI   r   r   Tzorders:r%  )r%  r   r~   r   r   r   r   r   r/  r   r  r  r	  )r   r   r
  r+  r%  	rawOrdersr  r4  r   r   r   r  r   symbolsArrayr  r   s                   r   handle_orderbybit.handle_order  s0   h ;;%%dllM4HE07DKOOGVR8		1b1##E:6V#	8YGIq#i.)A%%il3F H%F"GOMM&! * GLLN+q#l+,A!*\_!<NN66 - v+r   c                   #    U R                  5       I Sh  vN   SnSnSnU R                  SSU5      u  pASnU R                  SSU5      u  pQU R                  5       I Sh  vN nU R	                  USS5      nU R	                  USS5      nU R                  SSX!5      I Sh  vN n	U R                  U	5      I Sh  vN   SS	S
.n
U(       a  US:X  a  US-  nOUS-  nU(       d  U(       d  US:X  a  US-  nOUS-  nU(       a  US:X  a  US-  nOUS:X  a  US-  nOUS-  nU R                  XR                  U	5      5      /nU R                  X/X5      I Sh  vN $  GNE N N N N7f)aA  
watch balance and get the amount of funds available for trading or funds locked in orders

https://bybit-exchange.github.io/docs/v5/websocket/private/wallet

:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
Nr-   balancesr   Fr   ToutboundAccountInfowallet)rI   rM   rJ   z	:contractz:unifiedrI   z:spotrL   )
r   r   r   r   r   r   r   r   r  r   )r   r   r   r   r   r   rM   r   r   r   r  r   s               r   watch_balancebybit.watch_balanceS  s     !!! 99.$PVW99.$PVW--//..!U;>>'1e<//dFKK$$$)
 )#{*z)'7v~w&{*v~w&h&:-K;.K//-1F1Fs1KLM&&sM6JJJM 	" 0 L$6 KsZ   E&EA	E& E!A E&!E "E&:E";BE&E$E&E& E&"E&$E&c           	      6   U R                   c  0 U l         SnU R                  US5      nS n/ nS nUS:X  aY  SnU R                  US/ 5      n[        S[        U5      5       H)  n	U R                  X   S/ 5      n
U R	                  Xj5      nM+     UnUS:X  ax  U R                  US0 5      n[        S[        U5      5       HJ  n	U R                  US0 5      nU R                  US	5      nU R	                  X`R                  US
/ 5      5      nML     Un[        S[        U5      5       H  n	U R                  Xi   U5        M     Ub  U R                  U R                   U5      c  0 U R                   U'   XPR                   U   S'   U R                  US5      nXR                   U   S'   U R                  U5      U R                   U   S'   U R                  U R                   U   5      U R                   U'   SU-   nUR                  U R                   U   U5        g XPR                   S'   U R                  US5      nXR                   S'   U R                  U5      U R                   S'   U R                  U R                   5      U l         SnUR                  U R                   U5        g )Nbalancer   r;  rI   r   r   Br<  accountTypecoinr   r   r  r  z	balances:r:  )r@  r   r   r   array_concatr  parse_ws_balancer   r  safe_balancer	  )r   r   r
  r   r   r   rawBalancesaccountr   r   rA  r   r  s                r   handle_balancebybit.handle_balance  se   ^ <<DL1))G??7FB7D1c$i(OODGS"5"//? ) DH??7FB7D1c$i(q"500G"//__VU[]_=`a ) Dq#k*+A!!+.': ,t||W5=(*W%,0LL!&)))'48I1:LL!+.04Y0GDLL!*-$($5$5dll76K$LDLL!%/KNN4<<0+>#'LL ))'48I(1LL%'+||I'>DLL$,,T\\:DL$KNN4<<5r   c                    U R                  5       nU R                  USS5      nU R                  U5      nU R                  U/ SQ5      US'   U R                  USS5      US'   U R	                  US5      US	'   Ub>  U R                  U R                  U5      c  0 U R                  U'   X0R                  U   U'   g X0R                  U'   g )
Nr  rC  )availableToWithdrawffreerL  rN  llockedusedwalletBalancetotal)rH  r   safe_currency_coder  r   r   r@  )r   r@  rB  rH  
currencyIdcodes         r   rE  bybit.parse_ws_balance=  s    4 ,,.''f=
&&z2,,W6qr,,Wc8D++G_E"t||[9A,.[).5LL%d+!(LLr   c                    #    SU R                  5       US.nU R                  XT5      nU R                  XXb5      I S h  vN $  N7f)N	subscriber   req_idr   r   r  watch_multiple)r   r   r   r   r   r   r
  s          r   r   bybit.watch_topicsd  sE     oo'

 ++g.((WTTTTs   ;AAAr   r   r   r   c	           
         #    U R                  5       n	SU	US.n
U	UUUUS.nU R                  X5      nU R                  XXU R                  X5      5      I S h  vN $  N7f)NunsubscriberZ  )r   r   r   r   r   r\  )r   r   r   r   r   r   r   r   rE  r   r   subscriptionr
  s                r   r   bybit.un_watch_topicsm  sq     !
 * 0
 ++g.((WUYU`U`amU|}}}}s   AAAAc                   #    U R                  5         SnU R                  U5      nUR                  U5      nU R                  UR                  U5      nUc  U R                  5       S-   nU R                  U5      nSn	X-   n
U R                  U R                  U
5      U R                  U R                  5      [        R                  S5      nSU R                  X/S.nU R                  X5      nU R                  XX5        UI S h  vN $  N7f)Nauthenticatedi'  zGET/realtimehexauth)r   r   )check_required_credentialsr   reusableFuturer   subscriptionsr   number_to_stringhmacencodesecrethashlibsha256apiKeyr  r   )r   r   r   r   r   r   rd  
expiresIntexpirespathrf  	signaturer   r
  s                 r   r   bybit.authenticate~  s     '')%S!&&{3(<(<kJ **,u4J++J7G!D>D		$++d"3T[[5Mw~~_deIKKG kk'2GJJs>||s   DD
DD
c                 <   U R                  U/ SQ5      n Ub  US:w  a}  U R                  S-   U R                  U5      -   nU R                  U R                  S   X45        U R                  USS5      nU R                  U R                  S   XT5        [        U5      eU R                  US5      nUbm  U(       df  U R                  US5      nU R                  US	0 5      nU R                  US
5      n	U	S:X  a  [        SU-   5      e[        U R                  S-   U-   5      eg! [         ar  n
[        U
[        5      (       a0  SnUR                  X5        XR                  ;   a  UR                  U	 O#U R                  US5      nUR                  X5         S n
A
gS n
A
ff = f)N)rV  ret_coderetCode0 exactretMsgret_msgbroadsuccessr   r   rf  zAuthentication failed: Frd  r   T)r  r   rq  throw_exactly_matched_exception
exceptionsr   throw_broadly_matched_exceptionr   r   r   r   	Exceptionr  rejectri  )r   r   r
  rV  feedbackmsgr  r}  r   r   errorr   s               r   handle_error_messagebybit.handle_error_message  s   X !!'+JK	DCK77S=499W+==44T__W5Mt^(((IF44T__W5Ms]#H--oogy9G"7**7I>//'9bA%%gt4<-.G'.QRR'#(?@@ 		%!455-e1"6"66,,[9"..w@e1		s   DD 
F)A(FFc                    U R                  USSS5      nU R                  X5      (       a  g U R                  US5      nUS:X  d  US:X  a  U R                  X5        g U R	                  US5      nUb  U R                  X5        g U R                  US5      nUS:X  d  US:X  a  U R                  X5        g 0 S	U R                  _S
U R                  _SU R                  _SU R                  _SU R                  _SU R                  _SU R                  _SU R                  _SU R                  _SU R                  _SU R                  _SU R                  _SU R                  _SU R                  _SU R                  _SU R                  _SU R                  _U R                  U R                  U R                  U R                  U R                   U R"                  S.EnU R%                  Xs5      nUb	  U" X5        g ['        UR)                  5       5      n	[+        S[-        U	5      5       H,  n
X   nUR/                  X   5      S:  d  M   X{   nU" X5          g    U R                  US5      nUS:X  a  U R!                  X5        g g )Nr   r   r   r}  pongeventsubrY  r$  kliner  r&  r   rQ   publicTradedepthr<  r;  r  r  r  r  r  r  allLiquidation)r  r   r   r   rf  r`  r   r   	AUTH_RESP)r   r  r   handle_pongr   handle_subscription_statusr  rV  r7  r  r  rI  r  r  r  r0  handle_authenticatehandle_un_subscriber   r  r  r   r   rP  )r   r   r
  r   r}  r  r  methods
exacMethodr  r   keyr   r   s                 r   handle_messagebybit.handle_message  s   ""7GT2>$$V55""7I6v5F?V-  &1V-  '2E>e{2++F<
//
T&&
 T&&
 **	

 d((
 T''
 4--
 T++
 d))
 "4#6#6
 ..
 d33
 $//
 &t'<'<
 --
  422!
" d55#
$ $$ 00// 00,,33/
2 __W4
!v'GLLN#q#d)$A'Czz$'"a' v' % 0;$$V5 r   c                 (    U R                  5       SS.$ )Nrz   )r[  r   )r   )r   r   s     r   rz   
bybit.ping	  s    oo'
 	
r   c                 4    U R                  US5      Ul        U$ )Nr  )r   lastPongr   r   r
  s      r   r  bybit.handle_pong	  s    & ++GV<r   c                 x   U R                  US5      nU R                  US5      nSnU(       d  US:X  a/  U R                  UR                  U5      nUR                  S5        U$ [	        U R
                  S-   U R                  U5      -   5      nUR                  Xu5        XQR                  ;   a  UR                  U	 U$ )Nr  rx  rd  r   Trz  )	r   r   r  r	  r   r   rq  r  ri  )r   r   r
  r  rV  r   r   r  s           r   r  bybit.handle_authenticate5	  s    . //'95  )4%dai__V^^[AFNN4  	 (#		'8J(JKEMM%-222((5r   c                     U$ N r  s      r   r   bybit.handle_subscription_statusY	  s	     r   c                 f   U R                  US5      n[        UR                  R                  5       5      n[	        S[        U5      5       H  nXE   nXaR                  ;  a  M  UR                  S5      (       d  M0  UR                  U   nU R                  US5      nX8:w  a  MX  U R                  US/ 5      n	U R                  US/ 5      n
[	        S[        U	5      5       H:  nX   nX   nUS:H  =(       d    US:H  =(       d    US	:H  nU R                  XX5        M<     U R                  U5        M     U$ )
Nr[  r   r`  r   r   r   r%  r  r  )
r   r  ri  r  r   r   
startswithr!  clean_unsubscriptionclean_cache)r   r   r
  r   r  r   r   ra  subIdr   r   r  	unsubHashr  	usePrefixs                  r   r  bybit.handle_un_subscribej	  s)      (3F((--/0q#d)$A'K#7#77%%m44%33K@((t<> $|_b Q#'>>,@RTV#W q#m"45A - 0I.1G!(H!4 l'Z:O lU\`kUkI--fyT	 6
   .# %$ r   )r@  r  r%  r  r  )Y__name__
__module____qualname____firstlineno__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
   r   r  r/  r.  rF  rI  rV  rR  r   rd  rc  rz  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,  r0  r7  r   r=  rI  rE  r   r   r   r	   r  r  rz   r  r  r  r  __static_attributes____classcell__)r   s   @r   r   r      s~   Z# Zx
 :>^bkm $3 $X[ $L pt|~ 0JC 0Jy 0J	 0J[` 0Jil 0Jd im{  IK *Jc *J3 *Ji *Jy *Jbe *Jux *JX <@ "J "JS "JH 68 K KF K2 6:" E7 E E> 9=R sg sC s8 9; =C =s =M:F M:^ 8<B FW F7 F6" ?CQUdhqs ) ) )3 )^a )x|  ~B  yC )$ aesw  AC !E$tCy/ !EZ] !Emp !EF ^`  CT$s)_  Cdg  CD BFb T3 T3 TUX T.16 .1`
D 
4 @DB PS P PS\ P SW_a *!$s) *!C *!fo *!X PR !vT#Y !vVY !vF =? L L3 LC< C<J$3 <@d[] S SS S Sbfglbm S OSaenp !Sd3i !S !S[^ !Suyz  vA !SF LN sc sRU s4 9; HC Hs H&,F &,PBH 37TX\eg $UC $Us $URU $Ulpqvlw $UL 6:" js j jBw,v w,r 8<$]ajl "VW "VC "VWZ "Vquv~q "VH
8& 
87 
8*&H2T ;?r o oc o* BFTXac cs c3 cc chlmxhy c6;E ;Ez D 04$UYbd U UC Us Uimnsit U> 37r gC gc g6+f +4n,6 n,` *, /K /Kbw6V w6r%)N EG U SU  df ~ ~S ~7 ~[_`c[d ~x|  ~A  yB ~" .0 ,G6 Gt GR:6V :6x
6 
& ,"& "H "!& ! !r   r   )&ccxt.async_supportccxt ccxt.async_support.base.ws.cacher   r   r   r   r  rn  ccxt.base.typesr   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   r   r   r   r   async_supportr   r  r   r   <module>r     si     A  A   _  _  _  _  _ 4  * 0 . ' )w%D$$ w%r   