
    ":h8                        d dl Zd dlmZmZmZmZ d dlZd dl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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 d dlm Z  d d	lm!Z!  G d
 dejD                  jF                        Z#y)    N)
ArrayCacheArrayCacheBySymbolByIdArrayCacheBySymbolBySideArrayCacheByTimestamp)AnyBalancesIntLiquidationNumOrder	OrderBook	OrderSide	OrderTypePositionStrStringsTickerTickersTrade)Client)List)ExchangeError)AuthenticationError)ArgumentsRequired)
BadRequestc                       e Zd Zdef fdZd Zdddi fdedefdZd	 Zdi fde	d
e
dededef
dZddi fde	de	d
e
dededefdZd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i fde	defdZdefdZdi fdedefdZdSdZdddi fde	dedede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i fde	defd"Z"defd#Z#dSdef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	defd(Z)defd)Z*d* Z+d+ Z,ddi fde	dedede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defd.Z0i fde	defd/Z1defd0Z2dSd1Z3d2 Z4dddi fdedededee-   fd3Z5di fdedefd4Z6defd5Z7dddi fdedededee8   fd6Z9dSdedefd7Z:d8 Z;d9 Z<ddi fde	dededee=   fd:Z>defd;Z?dSd<Z@dddi fdedededeeA   fd=ZBdi fdedefd>ZCdefd?ZDdefd@ZEdSdAZFi fdeGfdBZHdefdCZIdSdDZJi fdEZKi i fdFe	dGe	dee	   dHee	   dIee	   f
dJZLi fdKZMdefdLZNdefdMZOdefdNZPdefdOZQdefdPZRdefdQZSdefdRZT xZUS )Tbybitreturnc                    | j                  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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 iddddddd*d+dd*d,d-dd id.d/d0iddd1d2g d3id4d5d6d7d8d9d:d;d<d=d>d?d@dAdBid4dCdDdEdFdGdHdIdJdKdLdMdNdOdBidP| j                  dQdRdS      S )TN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watchTradesForSymbolsz&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)r;   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)r;   r<   r>   r=   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)rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   135153060120240360720DWM)r6   r9   r0   r;   rA   iPF  )ping	keepAlive)hasurlsoptions	streaming)deep_extendsuperr   describerl   )self	__class__s    H/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/pro/bybit.pyrt   zbybit.describe   s   eT ; =d t $U	
    !% $U   !%    $T .u &u  0!"  #$ #(,"&,0## $#"&)-7> $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 		"UN@
 N N	    c                 ~    | j                  | j                  | j                  dd      d      }|| j                  d<   |S )N	requestIdr      )sumsafe_integerrp   )ru   rz   s     rw   
request_idzbybit.request_id   s9    HHT..t||[!LaP	$-[!rx   NFsymbolmethodc                   K   |rdnd}d }d }d }d }	| j                   d   d   }
|| j                  |      }	|	d   dk(  }|	d   }nK| j                  |d |      \  }}| j                  | j                  d      }| j                  |dd|      }|dk(  }|d	k(  }|rV| j                          d {   }| j                  |d
d      }| j                  |dd      }|r|s|s	|
|   d   }
nH|
|   d   }
n?|r	|
|   d	   }
n4|dk(  s|dk(  r"d }| j                  ||	|d      \  }}|
|   |   }
n|
|   d   }
| j                  |
      }
|
S 7 w)NrE   rD   rF   r    settleUSDCtypedefaultSettler;   r   Fr{   rB   rA   swapfuturer>   r=   )
ro   markethandle_market_type_and_paramssafe_stringrp   safe_string_2isUnifiedEnabled	safe_boolhandle_sub_type_and_paramsimplode_hostname)ru   r   	isPrivater   paramsaccessibilityisUsdcSettledisSpotr   r   urlr   r?   isUnifiedMarginisUnifiedAccountsubTypes                   rw   get_url_by_market_typez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   B'E )D>*BE c                 .    | j                  |g d      }|S )N)r   r   r   r   unifiedMargin)omit)ru   r   s     rw   clean_paramszbybit.clean_params   s    6#bcrx   r   sideamountpricec           	        K   | j                          d{    | j                  ||||||d      }| j                  d   d   d   d   }| j                  |       d{    t	        | j                               }	d|	|gt	        | j                               t	        | j                  d         d	d
}
| j                  ||	|
|	d       d{   S 7 7 t7 w)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>`
        NTrF   r    rE   rC   order.create
recvWindowzX-BAPI-TIMESTAMPzX-BAPI-RECV-WINDOWopreqIdargsheader)	load_marketscreate_order_requestro   authenticatestrr~   millisecondsrp   watch)ru   r   r   r   r   r   r   orderRequestr   rz   requests              rw   create_order_wszbybit.create_order_ws   s     @ !!!00tVUTZ\`aiit$Y/8$$$)*	  %((9(9(;$<&)$,,|*D&E

 ZZYDIII! 	" 	% J5   CCACCA-CCCCCidc           	        K   | j                          d{    | j                  |||||||      }| j                  d   d   d   d   }	| j                  |	       d{    t	        | j                               }
d|
|gt	        | j                               t	        | j                  d         dd	}| j                  |	|
||
d
       d{   S 7 7 t7 w)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>`
        NrF   r    rE   rC   order.amendr   r   r   T)	r   edit_order_requestro   r   r   r~   r   rp   r   )ru   r   r   r   r   r   r   r   r   r   rz   r   s               rw   edit_order_wszbybit.edit_order_ws  s     4 !!!..r64vuV\]iit$Y/8$$$)*	 %((9(9(;$<&)$,,|*D&E

 ZZYDIII! 	" 	% Jr   c                   K   | j                          d{    | j                  |||      }| j                  d   d   d   d   }| j                  |       d{    t	        | j                               }d|v r|d= d||gt	        | j                               t	        | j                  d         d	d
}| j                  ||||d       d{   S 7 7 {7 w)a  
        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>`
        NrF   r    rE   rC   orderFilterorder.cancelr   r   r   T)	r   cancel_order_requestro   r   r   r~   r   rp   r   )ru   r   r   r   r   r   rz   r   s           rw   cancel_order_wszbybit.cancel_order_ws3  s      !!!00VVDiit$Y/8$$$)*	L(]+  %((9(9(;$<&)$,,|*D&E

 ZZYDIII% 	" 	% Js5   CCACCA4CCCCCc                   K   | j                          d{    | j                  |      }|d   }d|z   }| j                  |dd|       d{   }| j                  |      }| j	                  | j
                  di       }| j                  |dd      }|d   s|dk7  rt        | j                  d	z         |d
|d   z   z  }|g}| j                  ||g||       d{   S 7 7 7 w)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:Fr6   rI   rJ   r;   z> watchTicker() only supports name tickers for contract markets.r   )
r   r   r   r   
safe_valuerp   r   r   r   watch_topics)	ru   r   r   r   messageHashr   rp   topictopicss	            rw   watch_tickerzbybit.watch_tickerU  s      !!!V$!&(//}fUU""6*//$,,rB  &)<f~%9"4TWW'gghhvd|##&&s[M66JJJ 	" V Ks4   C&C 6C&C"BC&C$C&"C&$C&symbolsc                   K   | j                          d{    | j                  |dd      }g }| j                  |d   dd|       d{   }| j                  |      }| j	                  | j
                  di       }| j                  |dd      }| j                  |      }g }t        dt        |            D ]5  }	||	   }
|j                  |dz   |
z          |j                  d||	   z          7 | j                  ||||       d{   }| j                  ri }|||d	   <   |S | j                  | j                  d	|      S 7 +7 7 >w)
a8  
        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   r7   rI   rJ   r   r   r   )r   market_symbolsr   r   r   rp   r   
market_idsrangelenappendr   
newUpdatesfilter_by_arrayrJ   )ru   r   r   messageHashesr   rp   r   	marketIdsr   imarketIdtickerresults                rw   watch_tickerszbybit.watch_tickersn  sT     !!!%%gtU;//
E>SYZZ""6*//$,,C  &)<OOG,	q#i.) 	9A |HMM%#+01  WQZ!78	9 ((mVVLL??F'-F6(#$M##DLL(GDD% 	" [ Ms4   EE3E
EB<EE:EEEc           	      <  K   | j                          d{    | j                  |dd      }| j                  | j                  di       }| j	                  |dd      }g }g }| j                  |      }g }t        dt        |            D ]K  }	||	   }
||	   }|j                  |dz   |
z          |j                  d|z          |j                  d	|z          M | j                  |d   dd|       d{   }| j                  |d
|||||       d{   S 7 7 %7 w)  
        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>`
        NFr7   rI   rJ   r   r   r   zunsubscribe:ticker:r   )r   r   r   rp   r   r   r   r   r   r   un_watch_topics)ru   r   r   rp   r   r   subMessageHashesr   r   r   r   r   r   s                rw   un_watch_tickerszbybit.un_watch_tickers  s3     !!!%%gtU;//$,,C  &)<OOG,	q#i.) 	AA |HQZFMM%#+01##I$67  !6!?@	A //
E>SYZZ))#x-Qacikqrrr 	" [rs4   DDCD2D3DDDDDc                 x   K   | j                          d{    | j                  |g|       d{   S 7 7 w)r   N)r   r   )ru   r   r   s      rw   un_watch_tickerzbybit.un_watch_ticker  s;      !!!**G9f=== 	"=   :6:8::clientc                    | j                  |dd      }| j                  |dd      }| j                  |di       }| j                  |d      d u}|rdnd}d }d }	|dk(  r| j                  |      }	|	d	   }n|d
k(  r|j                  d      }
t	        |
      }| j                  |
|dz
        }| j                  |d d |      }|d	   }| j                  | j                  |i       }| j                  |di       }| j                  ||      }| j                  |      }	| j                  |d      }||	d<   | j                  |      |	d<   |	| j                  |<   d|z   }|j                  | j                  |   |       y )Nr    r   datausdIndexPricer;   rA   snapshotr   deltar   r{   infots	timestampdatetimer   )r   	safe_dictparse_tickersplitr   safe_marketrJ   extendr}   iso8601resolve)ru   r   messager   
updateTyper   r   r   r   parsed
topicPartstopicLengthr   r   r   	rawTickermergedr   r   s                      rw   handle_tickerzbybit.handle_ticker  s   f   '26%%gvr:
~~gvr2!!$8DvZ*$&&t,FH%F7"S)Jj/K''
K!ODH%%hdDAFH%F^^DLL&"=Fvvr:I[[D1F&&v.F%%gt4	'{!\\)4z%V&(t||F+[9rx   c                   K   | j                          d{    | j                  |dd      }g }| j                  |d   dd|       d{   }| j                  |      }| j	                  |      }g }t        dt        |            D ]4  }||   }d|z   }	|j                  |	       |j                  d||   z          6 | j                  ||||       d{   }
| j                  r|
S | j                  | j                  d|      S 7 7 7 3w)a  
        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)ru   r   r   r   r   r   r   r   r   r   r   s              rw   watch_bids_askszbybit.watch_bids_asksF  s     !!!%%gtU;//
E?TZ[[""6*OOG,	q#i.) 	9A |H"X-EMM%   WQZ!78		9
 ((mVVLL??M##DMM8WEE 	" \ Ms4   DD3D
DBDD
0DD
Dc                    | j                  |d      }| j                  | j                  |d         d      }| j                  | j                  |d         d      }| j                  |dg       }| j                  |dg       }| j	                  |d   || j                  |      | j                  |d      | j                  |d      | j                  |d      | j                  |d      |d|      S )Nr   bidsr   asksr   r{   )r   r   r   ask	askVolumebid	bidVolumer   )r}   sort_by	aggregate	safe_listsafe_tickerr   safe_number)ru   	orderbookr   r   r   r   bestBidbestAsks           rw   parse_ws_bid_askzbybit.parse_ws_bid_aska  s    %%i=	||DNN9V+<=qA||DNN9V+<=qA..q"-..q"-X&"Y/##GQ/))'15##GQ/))'15	!
 	 		rx   rR   sincelimitc                 f   K   d|d<   | j                  ||gg|||       d{   }||   |   S 7 w)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
        r1   callerMethodNameN)watch_ohlcv_for_symbols)ru   r   	timeframer  r  r   r   s          rw   watch_ohlcvzbybit.watch_ohlcvr  sK      &2!"33fi5H4I5RWY_``f~i(( as    1/1symbolsAndTimeframesc                   K   | j                          d{    | j                  |d      }| j                  |dddd      }|d   }| j                  |dd|       d{   }g }	g }
t	        dt        |            D ]  }||   }| j                  |d      }| j                  |      }|d   }| j                  |d      }| j                  | j                  ||      }|	j                  d|z   d	z   |d
   z          |
j                  d|z   dz   |z           | j                  ||
|	|       d{   \  }}}| j                  r|j                  ||      }| j                  |||dd      }| j                  |||      S 7 d7 7 Tw)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   FTr2   r   r{   kline.r   r   ohlcv::::)r   get_list_from_object_valuesr   r   r   r   r   r   rQ   r   r   r   getLimitfilter_by_since_limitcreate_ohlcv_object)ru   r  r  r  r   r   marketSymbolsfirstSymbolr   	rawHashesr   r   r   symbolStringr   unfiedTimeframetimeframeIdr   r  storedfiltereds                        rw   r  zbybit.watch_ohlcv_for_symbols  s     !!!223GK++GT5$M#A&//UDZ\bcc	q#234 	TA'*D++D!4L[[.F!(+L"..tQ7O**4??O_]KX3c9F4LHI  \!9D!@?!RS	T +/*;*;CPY[a*b$b!	6??OOFE2E--feUAtL''	8DD) 	" d %cs6   FE:AFE=CF+F ,AF=F Fc           
        K   | j                          d{    | j                  |d      }| j                  |dddd      }|d   }| j                  |dd|       d{   }g }g }g }	t	        dt        |            D ]  }
||
   }| j                  |d      }| j                  |      }|d   }| j                  |d      }| j                  | j                  ||      }|j                  d|z   d	z   |d
   z          |j                  d|z   dz   |z          |	j                  d|z   dz   |z           d|i}| j                  |d||	||||       d{   S 7 >7 7 	w)ap  
        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   FTr2   r   r{   r  r   r   r  r  zunsubscribe::ohlcv::r  ohlcv)r   r  r   r   r   r   r   r   rQ   r   r   )ru   r  r   r   r  r  r   r  r   r   r   r   r   r   r!  r"  subExtensions                    rw   un_watch_ohlcv_for_symbolsz bybit.un_watch_ohlcv_for_symbols  s     !!!223GK++GT5$M#A&//UDZ\bcc	q#234 		aA'*D++D!4L[[.F!(+L"..tQ7O**4??O_]KX3c9F4LHI##I$<t$Co$UV  !7,!F!MP_!_`		a #$8
 ))#wP`bkms  vB  C  C  	C+ 	" d" Cs5   EEAEEC0EEEEEc                 R   K   d|d<   | j                  ||gg|       d{   S 7 w)aZ  
        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
        r1   r  N)r(  )ru   r   r  r   s       rw   un_watch_ohlcvzbybit.un_watch_ohlcv  s4      &2!"44vy6I5JFSSSSs   '%'c                 F   | j                  |di       }| j                  |d      }|j                  d      }t        |      }| j                  |d      }| j	                  |      }| j                  ||dz
        }	|j
                  j                  d      dkD  }
|
rdnd}| j                  |	d d |      }|d   }| j                  | j                  |      }|i | j                  |<   | j                  ||      8| j                  | j                  d	d
      }t        |      | j                  |   |<   | j                  |   |   }t        dt        |            D ](  }| j                  ||   |      }|j                  |       * d|z   dz   |z   }|||g}|j                  ||       y )Nr   r   r   r{   r;   rA   r   
OHLCVLimit  r   r  r  )r   r   r   r   find_timeframer   findr   ohlcvsr}   rp   r   r   parse_ws_ohlcvr   r   )ru   r   r   r   r   r   r   r"  r  r   r   
marketTyper   r   ohlcvsByTimeframer  r#  r   r   r   resolveDatas                        rw   handle_ohlcvzbybit.handle_ohlcv  s   . w3  '2[[%
*o&&z15''4	##Ja@(2-%V:
!!(D$
C! OODKK@$"$DKK??,i8@%%dllL$GE-B5-IDKK	*V$Y/q#d)$ 	"A((a&9FMM&!	"  &(4/);y&1{K0rx   c           	          |d   rdnd}| j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  ||      gS )	Nr<   turnovervolumestartopenhighlowclose)r}   r  )ru   r&  r   volumeIndexs       rw   r2  zbybit.parse_ws_ohlcv  s|      &,I%6jXeW-UF+UF+UE*UG,UK0
 	
rx   c                 F   K   | j                  |g||       d{   S 7 w)aB  
        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)ru   r   r  r   s       rw   watch_order_bookzbybit.watch_order_book"  s%      66xOOOOs   !!c                   K   | j                          d{    t        |      }|dk(  rt        | j                  dz         | j	                  |      }| j                  |d   dd|       d{   }| j                  |      }| j                  |d         }||d   rdnd}|d	   rd
}n|d   sS|d	   r"|dk7  rp|d
k7  rkt        | j                  dz         |dk7  rN|dk7  rI|dk7  rD|dk7  r?t        | j                  dz         |dk7  r"|dk7  r|dk7  rt        | j                  dz         g }g }t        dt        |            D ]S  }	||	   }
| j                  |
      }dt        |      z   dz   |z   }|j                  |       d|
z   }|j                  |       U | j                  ||||       d{   }|j                         S 7 7 Z7 w)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 symbolsFr3   r;   2     r=   d      zM watchOrderBookForSymbols() can only use limit 25 and 100 for option markets.r{      z^ watchOrderBookForSymbols() can only use limit 1, 50, 200 and 500 for swap and future markets.zN watchOrderBookForSymbols() can only use limit 1,50, and 200 for spot markets.
orderbook.r   
orderbook:)r   r   r   r   r   r   r   r   r   r   	market_idr   r   r   r  )ru   r   r  r   symbolsLengthr   r   r   r   r   r   r   r   r   r	  s                  rw   rA  z"bybit.watch_order_book_for_symbols/  s	     !!!GA#DGG.q$qrr%%g.//
ECSU[\\""6*WQZ(=!&>BEh&>(#%3,(  4C  *C  D  Dqju{#EUXL$TWW  0P  &P  Q  QQJUb[u|$TWW/%  A  Aq#g,' 	.AQZF~~f-H 3u:-3h>EMM% &/K  -	. ++COO	  C 	"
 ]6 Ps5   GGAG.G/EG0G1GGGc           	        K   | j                          d{    | j                  |dd      }d}| j                  |d      }|| j                  |d      }n| j	                  |d         }|d   rdnd}|t        |      z  }g }g }g }t        dt        |            D ]^  }	||	   }
| j	                  |
      }|d	   }|d
z   |z   }|j                  d|
z          |j                  d|
z          |j                  |       ` | j                  |d   dd|       d{   }| j                  |d|||||       d{   S 7 &7 &7 	w)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
        NFrI  r  r   r;   rD  rE  r   r   zunsubscribe:orderbook:rJ  r3   r	  )r   r   r}   r   r   r   r   r   r   r   r   )ru   r   r   channelr  firstMarketr   r   r   r   r   r   r   r   r   s                  rw   un_watch_order_book_for_symbolsz%bybit.un_watch_order_book_for_symbols]  sh     !!!%%gtU;!!&'2YYvw/F++gaj1K%f-B3E3u:q#g,' 	!AQZF[[(Fd|HcMH,E  !9F!BC##L6$9:MM% 	! //
ECSU[\\))#{G]Tdflntuuu- 	"* ]us4   ED<DED?E7E8E?EEc                 x   K   | j                          d{    | j                  |g|       d{   S 7 7 w)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   rP  ru   r   r   s      rw   un_watch_order_bookzbybit.un_watch_order_book  s;      !!!996(FKKK 	"Kr   c                    | j                  |d      }|j                  d      d   }|j                  j                  d      dk\  }| j                  |d      }|dk(  }| j	                  |di       }| j                  |d	      }	|rdnd
}
| j                  |	d d |
      }|d   }| j                  |d      }|| j                  vr| j                         | j                  |<   | j                  |   }|r'| j                  |||dd      }|j                  |       ni| j                  |dg       }| j                  |dg       }| j                  |d   |       | j                  |d   |       ||d<   | j                  |      |d<   d|z   }|| j                  |<   |j                  ||       |dk(  rK| j                  | j                  |   |      }i }|||<   || j                   |<   |j                  |d|z          y y )Nr   r   r{   r;   r   r   r   r   srA   r   r   bar   r   r   r   rJ  r_   r   )r   r   r   r0  r   r   r}   
orderbooks
order_bookparse_order_bookresetr  handle_deltasr   r   r  r   )ru   r   r   r   r  r   r   
isSnapshotr   r   r3  r   r   r   r	  r   r   r   r   bidasknewBidsAskss                        rw   handle_order_bookzbybit.handle_order_book  s   D   '2C #(A-0j(
~~gvr2##D#.%V:
!!(D$
C!%%gt4	$//)&*oo&7DOOF#OOF+	,,T69c3OHOOH%>>$R0D>>$R0Dy0$7y0$7%.Ik"$(LL$;Ij!'&0"+y+.C<**4??6+BFKF "K"(K$*DMM&!NN;	F(:; rx   c                 L    | j                  |dd      }|j                  |       y )Nr   r{   )parse_bid_ask
storeArray)ru   booksider   bidAsks       rw   handle_deltazbybit.handle_delta  s$    ##E1a0F#rx   c                 b    t        dt        |            D ]  }| j                  |||           y )Nr   )r   r   rf  )ru   rd  deltasr   s       rw   r\  zbybit.handle_deltas  s0    q#f+& 	3Ahq	2	3rx   c                 H   K   | j                  |g|||       d{   S 7 w)a6  
        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)ru   r   r  r  r   s        rw   watch_tradeszbybit.watch_trades  s'      22F8UE6RRRRs   " "c                   K   | j                          d{    | j                  |      }t        |      }|dk(  rt        | j                  dz         | j                  |      }| j                  |d   dd|       d{   }g }g }t        dt        |            D ]G  }	||	   }
| j                  |
      }d|d   z   }|j                  |       d|
z   }|j                  |       I | j                  ||||       d{   }| j                  r6| j                  |d      }| j                  |d	      }|j                  ||      }| j                  |||d
d      S 7 D7 7 `w)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 symbolsFr8   publicTrade.r   trade:r   r   T)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  )ru   r   r  r  r   rL  r   r   r   r   r   r   r   r   tradesfirsttradeSymbols                    rw   rj  zbybit.watch_trades_for_symbols  sk     !!!%%g.GA#DGG.n$noo""6*//
E=RXYYq#g,' 	.AQZF[[(F"VD\1EMM% "V+K  -	. ((mVV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           	        K   | j                          d{    | j                  |ddd      }| j                  |d   dd|       d{   }g }g }g }t        dt	        |            D ][  }||   }| j                  |      }	d|	d   z   }
|j                  |
       d|z   }|j                  |       |j                  d	|z          ] | j                  |d
|||||       d{   S 7 7 7 w)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   unWatchTradesForSymbolsrm  r   zunsubscribe:trade:rn  ro  )r   r   r   r   r   r   r   r   )ru   r   r   r   r   r   r   r   r   r   r   r   s               rw   un_watch_trades_for_symbolsz!bybit.un_watch_trades_for_symbols  s
     !!!%%gtUDA//
EC\^deeq#g,' 	7AQZF[[(F"VD\1EMM% .7K  -##Hv$56	7 ))#x-Qacikqrrr 	"e ss4   C,C&2C,	C(
BC,!C*"C,(C,*C,c                 x   K   | j                          d{    | j                  |g|       d{   S 7 7 w)aZ  
        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   rt  rR  s      rw   un_watch_tradeszbybit.un_watch_trades%  s;      !!!55vhGGG 	"Gr   c                 j   | j                  |di       }| j                  |d      }|}|j                  d      }|j                  j	                  d      dk\  }|rdnd}| j                  |d      }	| j                  |	d d |      }
|
d   }| j                  | j                  |      }|7| j                  | j                  d	d
      }t        |      }|| j                  |<   t        dt        |            D ](  }| j                  ||   |
      }|j                  |       * d|z   }|j                  ||       y )Nr   r   r   r;   r   rA   r{   r   tradesLimitr.  rn  )r   r   r   r   r0  r   ro  r}   rp   r   r   r   parse_ws_trader   r   )ru   r   r   r   r   ro  partsr   r3  r   r   r   r#  r  jr   r   s                    rw   handle_tradeszbybit.handle_trades2  s,   ( w3  '2C (A- &VZ
##E1-!!(D$
C!f5>%%dllM4HE&F"(DKKq#f+& 	"A((F;FMM&!	" $f,v{+rx   c                    | j                  |g d      }d|v }|rdnd}||d   }| j                  |d      }| j                  ||d |      }|d   }| j                  |dd	      }| j	                  |d
      }	d }
| j                  |d      }|	|rdnd}	n|}
| j                  |d      }| j                  |dd      }| j                  |d      }| j                  |||| j                  |      ||d |	|
||d d d|      S )N)r   TvBTrA   r;   r   rU  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   )ru   rC   r   r   
isContractr3  r   r   r   r   r  r  r   r   orderIds                  rw   ry  zbybit.parse_ws_tradeZ  s=   @ 7em
#-Z6
J##E3/!!(FD*E!''sC8	%%eS1OOE3'<56D L  ,##E34""5#."Y/( 
  	rx   c                 X    |j                  d      dk\  ry|j                  d      dk\  ryy)Nr;   r   z
v5/privater?   rB   )r0  )ru   r   s     rw   get_private_typezbybit.get_private_type  s-    88Fq XXl#q(rx   c                   K   d}d}| j                          d{    || j                  |      }|d|z   z  }| j                  |d||       d{   }| j                  |       d{    dddd	}| j	                  || j                  |            }	| j                  ||g|	g|       d{   }
| j                  r|
j                  ||      }| j                  |
|||d      S 7 7 7 7 =w)
a  
        watches information on multiple trades made by the user

        https://bybit-exchange.github.io/docs/v5/websocket/private/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
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        r0   myTradesN:T
ticketInfo	executionuser.openapi.perp.trader;   r?   rB   
r   r   r   r   r   r  r   r   r  filter_by_symbol_since_limit)ru   r   r  r  r   r   r   r   topicByMarketr   ro  s              rw   watch_my_tradeszbybit.watch_my_trades  s     ! !!![[(F3<'K//ffMM$$$ "-

 t/D/DS/IJ(({meWfMM??OOFE2E00tTT 	" N$ NsF   C/C'6C/C)C/*C++AC//C-08C/)C/+C/-C/c           	        K   d}d}d}| j                          d{    || j                  |      }|d|z   z  }| j                  |d||       d{   }| j                  |       d{    ddd	d
}| j	                  || j                  |            }| j                  |dg |g|g|g|       d{   S 7 7 h7 Q7 
w)a  
        unWatches information on multiple trades made by the user

        https://bybit-exchange.github.io/docs/v5/websocket/private/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
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        r0   zunsubscribe:myTradesr  Nr  Tr  r  r  r  r   r   r   r   r   r  r   )	ru   r   r   r   r   subHashr   r  r   s	            rw   un_watch_my_tradeszbybit.un_watch_my_trades  s      !,!!![[(FsV|#G//ffMM$$$ "-

 t/D/DS/IJ))#z2}wiZ_Y`bhiii 	" N$ jsF   CB:6CB<C,B>-AC5C 6C<C>C Cc                 "   | j                  |d      }|dk(  }| j                  |dg       }t        |t              s| j                  |dg       }| j                  -| j                  | j                  dd      }t        |      | _        | j                  }i }| j                  ddg       }	t        d	t        |            D ]o  }
||
   }d }|r| j                  |      }n7| j                  |d
d      }| j                  ||	      sD| j                  |      }|d   }d||<   |j                  |       q t        |j                               }t        d	t        |            D ]  }
d||
   z   }|j!                  ||        d}|j!                  ||       y )Nr   r  r   r   rx  r.  r0   rM   r   execTyper   r   Tz	myTrades:r  )r   r   
isinstancelistr  r}   rp   r   handle_optionr   r   ry  in_arrayparse_trader   keysr   )ru   r   r   r   r;   r   r  ro  r   rM   r   rawTrader   r  r   r  currentMessageHashr   s                     rw   handle_my_tradeszbybit.handle_my_trades  s   ~   '2$w3$%??426D== %%dllM4HE259DM,,_>OQSTq#d)$ 	"AAwHF,,X6  ++Hj"E}}X?))(3H%F"GFOMM&!	" GLLN#q#d)$ 	7A!,tAw!6NN6#56	7 !v{+rx   c                   K   | j                          d{    d}d}| j                  |      s%| j                  |      }ddj                  |      z   }| j	                  |d      }| j                  |d||       d{   }d|z   }| j                  |      }	| j                  |       d{    | j                  |	|       | j                  }
| j                  dd	d      }| j                  dd
d      }|r2|r0|
.|	j                  d	       d{   }| j                  ||||d      S dg}| j                  ||g||       d{   }| j                  r|S | j                  |
|||d      S 7 W7 7 7 c7 0w)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>`
        Nr9   r   r  ,r   T	positionsrK   rL   position)r   is_emptyr   joinr   r   r   r   set_positions_cacher  r  r   filter_by_symbols_since_limitr   r   )ru   r   r  r  r   r   r   r  r   r   cacherK   rL   r   r   newPositionss                   rw   watch_positionszbybit.watch_positionsB  s     !!!!}}W%))'2G'!22K&&w2//T66RR!K/S!$$$  1!%!3!34DF^`d!e!%!3!34DF^`d!e!&<#]]+CDDH55hPUW[\\!..s[M66RR??11%%PTUU- 	" S 	% E SsY   E8E-A'E8>E0?.E8-E2.A"E8E44E8E6(E80E82E84E86E8c                     | j                   y | j                  ddd      }|r@d}||j                  vr/|j                  |       | j	                  | j
                  ||       y y t               | _         y )Nr9   rK   T)r  r  futuresr   spawnload_positions_snapshotr   )ru   r   r   rK   r   s        rw   r  zbybit.set_positions_cachef  sn    >>%!%!3!34DF^`d!e!2K6>>1k*

477M 2 67DNrx   c                   K   | j                  d ddd      | j                  d ddd      g}t        j                  |  d {   }t               | _        | j                  }t        dt        |            D ]7  }||   }t        dt        |            D ]  }||   }	|j                  |	        9 |j                  |   }
|
j                  |       |j                  |d       y 7 w)Nr   r>   )r   r   r<   r   r  )
fetch_positionsasynciogatherr   r  r   r   r   r  r   )ru   r   r   fetchFunctionspromisesr  r   r  iir  r   s              rw   r  zbybit.load_positions_snapshotr  s        8'LM  9'MN
 !8813q#h-( 	'A IAs9~. '$R=X&'	' ,uuj) 9s   A C&C$B"C&c                    | j                   t               | _         | j                   }g }| j                  |dg       }t        dt	        |            D ]  }||   }| j                  |      }| j                  |d      }	|j                  |       |	|	dk(  r2d|d<   |j                  |       d|d<   |j                  |       d |d<   u|j                  |        | j                  |d      }
t        dt	        |
            D ]f  }|
|   }|j                  d      }|d	   }|j                  d
      }| j                  |d|d      }| j                  |      rU|j                  ||       h |j                  |d       y )Nr   r   r   r   longshortzpositions::r  r{   r  r   Fr  )r  r   r   r   r   parse_positionr   r   find_message_hashesr   r   r  r   )ru   r   r   r  r  rawPositionsr   rawPositionr  r   r   r   rz  symbolsStringr   r  s                   rw   handle_positionszbybit.handle_positions  s   P >>!57DNw;q#l+, 	'A&q/K**;7H##Hf5D )|trz $* X&#* X&#'  X&#	'$ 00Gq#m,- 	7A'*K%%d+E!!HM#))#.G,,\8WeTI==+y+6	7 	|[1rx   c                   K   | j                          d{    | j                  |      }|d   }| j                  |dd|       d{   }| j                  |      }d}| j	                  |ddd      \  }}d|z   }|dz   |d	   z   }	| j                  ||g|	g|       d{   }
| j                  r|
S | j                  | j                  |g||d
      S 7 7 7 6w)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   handle_option_and_paramsr   r   r  liquidations)ru   r   r  r  r   r   r   r   r   r   newLiquidations              rw   watch_liquidationszbybit.watch_liquidations  s      !!!V$!//?RTZ[[""6*66v?RT\^kl&/vd|+#00{meWfUU??!!11$2C2CfXuV[]abb 	" \ Vs4   CC1CC	AC C!3CCCc                    t        |d   t              r| j                  |dg       }t        dt	        |            D ]  }||   }| j                  |d      }| j                  |d dd      }|d   }| j                  ||      }	| j                  | j                  |      }
|
(| j                  | j                  dd      }t        |      }
|
j                  |	       |
| j                  |<   |j                  |	gd	       |j                  |	gd
|z           y | j                  |di       }| j                  |d      }| j                  |d dd      }|d   }| j                  ||      }	| j                  | j                  |      }
|
(| j                  | j                  dd      }t        |      }
|
j                  |	       |
| j                  |<   |j                  |	gd	       |j                  |	gd
|z          y )Nr   r   rU  r   rA   r   liquidationsLimitr.  r  r  )r  r  r  r   r   r   r   parse_ws_liquidationr   r  r}   rp   r   r   r   r   )ru   r   r   rawLiquidationsr   rawLiquidationr   r   r   r  r  r  s               rw   handle_liquidationzbybit.handle_liquidation  s   < gfot,"nnWfbAO1c/23 I!0!3++NC@))(D"jI)"77O#t/@/@&I' --dll<OQUVE#-e#4L##K0,8!!&)}n=}.>.GHI "^^GVR@N''AH%%hb*EFH%F33NFKK??4+<+<fEL#))$,,8KTR)%0,(4Df%NNK=.9NNK=*:V*CDrx   c                 4   | j                  |dd      }| j                  ||dd      }| j                  |dd      }| j                  ||d   | j	                  |dd      | j                  |d	      | j	                  |d
d      d d || j                  |      d	      S )Nr   rU  r   rA   updatedTimer~  sizer  contractSizer   r  )	r   r   	contractsr  r   	baseValue
quoteValuer   r   )r   r   r  safe_liquidationsafe_number_2r  r   )ru   r  r   r   r   s        rw   r  zbybit.parse_ws_liquidation'  s    $ %%k8SA!!(FB
C'']CH	$$X&++KE ,,V^D''WcB"Y/
&
 
 
	rx   c                   K   | j                          d{    d}d}|| j                  |      }|d|z   z  }| j                  |d||       d{   }| j                  |       d{    ddgdgdgd	}| j	                  || j                  |            }	| j                  ||g|	|       d{   }
| j                  r|
j                  ||      }| j                  |
|||d      S 7 7 7 7 =w)
a7  
        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>`
        Nr5   ordersr  Tr  	stopOrderuser.openapi.perp.orderr  r  )ru   r   r  r  r   r   r   r   topicsByMarketr   r  s              rw   watch_orderszbybit.watch_ordersH  s     !!![[(F3<'K//ffMM$$$k*y./ 

 1F1Fs1KL(({mVVLL??OOFE2E00tTT# 	" N$ MsF   C2C*:C2C,C2*C.+AC22C038C2,C2.C20C2c           	        K   | j                          d{    d}d}d}|| j                  |      }|d|z   z  }| j                  |d||       d{   }| j                  |       d{    ddgdgd	gd
}| j	                  || j                  |            }| j                  |dg |g|g||       d{   S 7 7 k7 T7 
w)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>`
        Nr5   zunsubscribe:ordersr  r  Tr  r  r  r  r  )	ru   r   r   r   r   r  r   r  r   s	            rw   un_watch_orderszbybit.un_watch_ordersg  s      !!!*[[(FsV|#G//ffMM$$$k*y./ 

 1F1Fs1KL))#xk]WIW]_efff 	" N$ gsF   CB=<CB?C,C-AC8C9C?CCCc                     | j                  |d      }| j                  |d      }| j                  |      }|j                  ||       y )Nr   r   )r   r   parse_orderr   )ru   r   r   r   r   r  s         rw   handle_order_wszbybit.handle_order_ws  sD    * &&w8~~gv.  &uk*rx   c                    | j                   -| j                  | j                  dd      }t        |      | _         | j                   }| j	                  |dg       }| j	                  |di       }| j                  |d      }|dk(  }|s| j	                  |d|      }i }	t        dt        |            D ]J  }
d }|r| j                  ||
         }n| j                  ||
         }|d   }d	|	|<   |j                  |       L t        |	j                               }t        dt        |            D ]  }
d
||
   z   }|j                  ||        d}|j                  ||       y )NordersLimitr.  r   r   categoryr;   r   r   Tzorders:r  )r  r}   rp   r   r   r   r   r   parse_ws_spot_orderr  r   r  r  r   )ru   r   r   r  r  	rawOrdersrp  r  r   r   r   r   r   symbolsArrayr  r   s                   rw   handle_orderzbybit.handle_order  s_   h ;;%%dllM4HE07DKOOGVR8		1b1##E:6V#	8YGIq#i.) 	"AF11)A,?)))A,7H%F"GFOMM&!	" GLLN+q#l+, 	7A!*\!_!<NN6#56	7 v{+rx   c                    | j                  |dd      }| j                  |dd      }| j                  ||d d      }| j                  |dd      }| j                  |dd	      }|d
k(  rd }| j                  |dd      }| j                  | j                  |dd            }	| j	                  |dd      }
| j                  |dd      }| j                  |dd      }d }| j                  |dd      }| j	                  |dd      }||j                  d      dk\  rd}|dk(  r|
dk(  r|}n| j                  |dd      }d }| j                  |dd      }|-|d
k7  r(| j                  |d       }| j                  |      }||d!}| j                  | j                  |d"            }| j                  i d#|d$|d%| j                  |d&d'      d(|d)| j                  |      d*|d|d+|d|d,d d|
d	|d-|d"|d.| j                  |d/      d0| j                  |d1      d2| j                  |d2      ||| j                  |d3      |d |	|d4|      S )5Nr   r  rU  r   r;   OcreatedTimer  r   0z
cumExecQtyXorderStatusr  r   Er  ftimeInForceZcumExecValuer  	orderTyper   r   r  orderQtyqtyn
cumExecFeeN)r  currencytriggerPricer   r   clientOrderIdcorderLinkIdr   r   lastTradeTimestampr   postOnly	stopPricetakeProfitPrice
takeProfitstopLossPricestopLoss
reduceOnlyavgPrice)r   r  averagefilled	remainingstatusr  )r   safe_symbolr  parse_order_statussafe_string_lower_2r0  r   safe_currency_code	omit_zero
safe_orderr   r   )ru   r  r   r   r   r   r   r   r  r  r   r  r   r   r  r   r  feeCostfeeCurrencyIdfeeCurrencyCoder
  s                        rw   r  zbybit.parse_ws_spot_order  s   R sI6%%eS(;!!(FD&A''sMB	""5#w7C<E##E3=((););E3)VW''sF;!//sMJ((]C!!%n=''sK@499X#6!#;D8F''z5AF$$UC>7c> ,,UC8M"55mDO+C ~~d&6&6un&MN  
E 
" 
 T//sMJ 
 	 

 Y/ 
 !"4 
 f 
 D 
 ; 
  
 D 
 U 
  
 L 
 t//|D 
  T--eZ@! 
" $//%># 
$ ''z:1 
2 3 	rx   c                   K   | j                          d{    d}d}d}| j                  dd|      \  }}d}| j                  dd|      \  }}| j                          d{   }| j	                  |dd      }| j	                  |dd      }| j                  dd||       d{   }	| j                  |	       d{    dd	d
}
|r|dk(  r|dz  }n|dz  }|s|s|dk(  r|dz  }n|dz  }|r|dk(  r|dz  }n|dk(  r|dz  }n|dz  }| j                  |
| j                  |	            g}| j                  |	|g||       d{   S 7 37 7 7 7 w)ai  
        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)r;   r?   r<   z	:contractz:unifiedr;   z:spotr>   )
r   r   r   r   r   r   r   r   r  r   )ru   r   r   r   r   r   r?   r   r   r   r  r   s               rw   watch_balancezbybit.watch_balance  s     !!! 99.$PVWf99.$PVW--//..!U;>>'1e<//dFFKK$$$)
 )#{*z)'7v~w&{*v~w&h&:-K;.K//-1F1Fs1KLM&&s[M66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           	      0   | j                   i | _         d}| j                  |d      }d }g }d }|dk(  rYd}| j                  |dg       }t        dt        |            D ]*  }	| j                  ||	   dg       }
| j	                  ||
      }, |}|dk(  rw| j                  |di       }t        dt        |            D ]J  }	| j                  |di       }| j                  |d	      }| j	                  || j                  |d
g             }L |}t        dt        |            D ]  }	| j                  ||	   |        || j                  | j                   |      i | j                   |<   || j                   |   d<   | j                  |d      }|| j                   |   d<   | j                  |      | j                   |   d<   | j                  | j                   |         | j                   |<   d|z   }|j                  | j                   |   |       y || j                   d<   | j                  |d      }|| j                   d<   | j                  |      | j                   d<   | j                  | j                         | _         d}|j                  | j                   |       y )Nbalancer   r&  r;   r   r   Br'  accountTypecoinr   r   r   r   z	balances:r%  )r*  r   r   r   array_concatr  parse_ws_balancer}   r   safe_balancer   )ru   r   r   r   r   r   rawBalancesaccountr   r   r+  r   r   s                rw   handle_balancezbybit.handle_balance  s   ^ <<DL1))G??7FB7D1c$i( @OODGS"5"//Q?@ DH??7FB7D1c$i( bq"500G"//T__VU[]_=`ab Dq#k*+ 	;A!!+a.':	;t||W5=(*W%,0DLL!&)))'48I1:DLL!+.04Y0GDLL!*-$($5$5dll76K$LDLL!%/KNN4<<0+>#'DLL ))'48I(1DLL%'+||I'>DLL$,,T\\:DL$KNN4<<5rx   c                    | j                         }| j                  |dd      }| j                  |      }| j                  |g d      |d<   | j                  |dd      |d<   | j	                  |d      |d	<   |>| j                  | j                  |      i | j                  |<   || j                  |   |<   y || j                  |<   y )
NrW  r-  )availableToWithdrawr  freer5  r6  llockedusedwalletBalancetotal)r2  r   r  r  r   r   r*  )ru   r*  r,  r2  
currencyIdcodes         rw   r/  zbybit.parse_ws_balancey  s    4 ,,.''f=
&&z2,,W6qr,,Wc8D++G_E"t||[9A,.[).5DLL%d+!(DLLrx   c                    K   d| j                         |d}| j                  ||      }| j                  ||||       d {   S 7 w)N	subscriber   req_idr   r~   r   watch_multiple)ru   r   r   r   r   r   r   s          rw   r   zbybit.watch_topics  sL     oo'

 ++gv.((mWmTTTTs   >A AAr   r   r   r   c	           
         K   | j                         }	d|	|d}
|	||||d}| j                  |
|      }| j                  ||||| j                  ||             d {   S 7 w)Nunsubscriber@  )r   r   r   r   r   rB  )ru   r   r   r   r   r   r   r   r'  r   r   subscriptionr   s                rw   r   zbybit.un_watch_topics  s{     !
 * 0
 ++gv.((mWmUYU`U`amo{U|}}}}s   AA"A A"c                    K   | j                          d}| j                  |      }|j                  |      }| j                  |j                  |      }|| j                         dz   }| j                  |      }d}	|	|z   }
| j                  | j                  |
      | j                  | j                        t        j                  d      }d| j                  ||gd}| j                  ||      }| j                  ||||       | d {   S 7 w)Nauthenticatedi'  zGET/realtimehexauth)r   r   )check_required_credentialsr   r   r   subscriptionsr   number_to_stringhmacencodesecrethashlibsha256apiKeyr   r   )ru   r   r   r   r   r   rH  
expiresIntexpirespathrJ  	signaturer   r   s                 rw   r   zbybit.authenticate  s     '')%S!{+(<(<kJ **,u4J++J7G!D'>D		$++d"3T[[5Mw~~_deIKK)G kk'62GJJsK+>||s   DDDDc                 $   | j                  |g d      }	 ||dk7  r| j                  dz   | j                  |      z   }| j                  | j                  d   ||       | j                  |dd      }| j                  | j                  d   ||       t        |      | j                  |d      }|g|se| j                  |d      }| j                  |d	i       }| j                  |d
      }	|	dk(  rt        d|z         t        | j                  dz   |z         y# t        $ rn}
t        |
t              r0d}|j                  |
|       ||j                  v r2|j                  |= n$| j                  |d      }|j                  |
|       Y d }
~
yd }
~
ww xY w)N)r=  ret_coderetCoder   exactretMsgret_msgbroadsuccessr   r   rJ  zAuthentication failed: FrH  r   T)r  r   jsonthrow_exactly_matched_exception
exceptionsr   throw_broadly_matched_exceptionr   r   r   r   	Exceptionr  rejectrL  )ru   r   r   r=  feedbackmsgr`  r^  r   r   errorr   s               rw   handle_error_messagezbybit.handle_error_message  s   X !!'+JK	DCK77S=499W+==44T__W5MtU]^(((IF44T__W5MsT\]#H--oogy9G"7**7I>//'9bA%%gt4<-.G'.QRR'#(?@@ 		%!45-e[1&"6"66,,[9"..w@e[1		s   DD 	F!A$F

Fc                    | j                  ||      ry | j                  |d      }|dk(  r| j                  ||       y | j                  |d      }|| j                  ||       y | j                  |d      }|dk(  r| j	                  ||       y | j                  |ddd      }i d| j                  d	| j                  d
| j                  d| j                  d| j                  d| j                  d| j                  d| j                  d| j                  d| j                  d| j                  d| j                  d| j                  d| j                  d| j                  d| j                  d| j                  | j                  | j                  | j                  | j                   | j"                  d}| j%                  ||      }|
 |||       y t'        |j)                               }	t+        dt-        |	            D ].  }
|	|
   }|j/                  |	|
         dk\  s ||   } |||        y  | j                  |d      }|dk(  r| j!                  ||       y y )Nr^  pongeventsubr   r   r   r	  kliner  r  r   rC   publicTradedepthr'  r&  r  r  r  r  r  allLiquidation)r   r   r   rJ  rE  r   r   	AUTH_RESP)rj  r   handle_pongr}   handle_subscription_statusr   r`  r6  r  r   r|  r3  r  r  r  r  handle_authenticatehandle_un_subscriber   r  r  r   r   r0  )ru   r   r   r^  rl  rm  r   methods
exacMethodr  r   keyr   r   s                 rw   handle_messagezbybit.handle_message	  s   $$VW5""7I6fVW-  &1VW-  '2E>++FG<""7GT2>
//
T&&
 T&&
 **	

 d((
 T''
 4--
 T++
 d))
 "4#6#6
 ..
 $//
 &t'<'<
 --
 422
  d55!
" D$$#
$ !00// 00,,33-
0 __We4
!vw'GLLN#q#d)$ 	Aq'Czz$q'"a' vw'	 0;$$VW5 rx   c                 (    | j                         ddS )Nrl   )rA  r   )r~   )ru   r   s     rw   rl   z
bybit.pingT	  s    oo'
 	
rx   c                 4    | j                  |d      |_        |S )Nrl  )r}   lastPongru   r   r   s      rw   rt  zbybit.handle_pongZ	  s     ++GV<rx   c                 l   | j                  |d      }| j                  |d      }d}|s|dk(  r/| j                  |j                  |      }|j                  d       |S t	        | j
                  dz   | j                  |      z         }|j                  ||       ||j                  v r|j                  |= |S )Nr`  rZ  rH  r   Tr[  )	r   r}   r  r   r   r   ra  rf  rL  )ru   r   r   r`  r=  r   r   ri  s           rw   rv  zbybit.handle_authenticateh	  s      //'95  )4%dai__V^^[AFNN4  	 (#		'8J(JKEMM%-f222((5rx   c                     |S N r  s      rw   ru  z bybit.handle_subscription_status	  s	     rx   c                    | j                  |d      }t        |j                  j                               }t	        dt        |            D ]  }||   }||j                  vr|j                  d      s)|j                  |   }| j                  |d      }||k7  rP| j                  |dg       }	| j                  |dg       }
t	        dt        |	            D ]  }|	|   }|
|   }| j                  |||       ! | j                  |        |S )NrA  r   rE  r   r   r   )
r   r  rL  r  r   r   
startswithr  clean_unsubscriptionclean_cache)ru   r   r   r   r  r   r   rF  subIdr   r   r{  	unsubHashr  s                 rw   rw  zbybit.handle_un_subscribe	  s      (3F((--/0q#d)$ 	/Aq'K6#7#77%%m4%33K@((t<E> $|_b Q#'>>,@RTV#W q#m"45 JA -a 0I.q1G--fgyIJ   .!	/" rx   r  )V__name__
__module____qualname__r   rt   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  r(  r*  r6  r2  r   rB  rA  rP  rS  r`  rf  r\  r   rk  rj  rt  rv  r|  ry  r  r  r  r  r   r  r  r  r  r
   r  r  r  r   r  r  r  r  r  r   r(  r3  r/  r   r   r   rj  r{  rl   rt  rv  ru  rw  __classcell__)rv   s   @rw   r   r      s9   O# Ob
 :>^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D 68 K KF K2 6:" E7 E E> 9=R sg sC s8 :< >S > >M:F M:^ 8<B FW F7 F6" 8<$]ajl ) )C )WZ )quvzq{ )$ aesw  AC !E$tCy/ !EZ] !Emp !EF ^`  CT$s)_  Cdg  CD ;?r T3 Tc T.16 .1`
D 
4 @DB PS P PS\ P SW_a ,!$s) ,!C ,!fo ,!\ NP !vW !vTW !vF =? L L3 LB< B<H$3 <@d[] S SS S Sbfglbm S OSaenp !Sd3i !S !S[^ !Suyz  vA !SF JL s sPS s4 9; HC Hs H&,F &,PBH 37TX\eg UC Us URU Ulpqvlw U@ 6:" js j j8^,v ^,@ 8<$]ajl "VW "VC "VWZ "Vquv~q "VH
8& 
87 
8*&H2T BFTXac cs c3 cc chlmxhy c6;E ;EzB 04$UYbd U UC Us Uimnsit U> 37r gC gc g8+f +4m,6 m,^AF *, /K /Kbw6V w6r%)N EG U UW  fh ~ ~S ~49 ~]abe]f ~z~  @C  {D ~" .0 ,G6 GR96V 96v
6 
& & : " &  rx   r   )$ccxt.async_supportccxt ccxt.async_support.base.ws.cacher   r   r   r   r  rQ  ccxt.base.typesr   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   async_supportr   r  rx   rw   <module>r     sf     A  A   Y  Y  Y  Y  Y 4  * 0 . 'c&D$$ c&rx   