
    eiU                       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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" d d
lm#Z#  G d dej$        j%                  Z%dS )    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                   D    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dTdZdddi fde	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	defd#Z"defd$Z#dTd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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e	         defd/Z0i fde	defd0Z1defd1Z2dTd2Z3d3 Z4dddi fdedededee-         fd4Z5di fdedefd5Z6defd6Z7dddi fdedededee8         fd7Z9dTdedefd8Z:d9 Z;d: Z<di fdedefd;Z=ddi fde	dededee>         fd<Z?defd=Z@dTd>ZAdddi fdedededeeB         fd?ZCdi fdedefd@ZDdefdAZEdefdBZFi fdeGfdCZHdefdDZIdTdEZJi fdFZKi i fdGe	dHe	dedIee	         dJee	         f
dKZLi fdLZMdedeNfdMZOdefdNZPdefdOZQdefdPZRdefdQZSdefdRZTdefdSZU xZVS )Ubybitreturnc                 D   |                      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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/d0d1idd2d3d4d5d6d7d8d-d7d9d:d0d1idd&d'd(d)d*d;d<d-d;d=d>d0d1id?d@dAidddBdCg dDidEdFdGdHdIdJdKdLdMdNdOdPdQdRdSidEdTdUdVdWdXdYdZd[d\d]d^d_d`dSida| j        dbdcdd          S )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)rH   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)rH   rI   rK   rJ   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_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   135153060120240360720DWM)r8   r;   r2   rH   rN   iPF  )ping	keepAlive)hasurlsoptions	streaming)deep_extendsuperr   describery   )self	__class__s    L/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/pro/bybit.pyr   zbybit.describe   s   eT 2 2 ; ; = ='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 0d 	" kY@
 Y@
 Y Y Y	    c                     |                                   |                     |                     | j        dd          d          }|| j        d<   |                                  |S )N	requestIdr      )lock_idsumsafe_integerr}   	unlock_id)r   r   s     r   
request_idzbybit.request_id   sX    HHT..t|[!LLaPP	$-[!r   NFsymbolmethodc                 
  K   |rdnd}d }d }d }d }	| j         d         d         }
|*|                     |          }	|	d         dk    }|	d         }nS|                     |d |          \  }}|                     | j        d          }|                     |dd|          }|dk    }|d	k    }|rl|                                  d {V }|                     |d
d          }|                     |dd          }|r|s|s|
|         d         }
nf|
|         d         }
nW|r|
|         d	         }
nF|dk    s|dk    r,d }|                     ||	|d          \  }}|
|         |         }
n|
|         d         }
| 	                    |
          }
|
S )NrR   rQ   rS   r"   settleUSDCtypedefaultSettlerH   r   Fr   rO   rN   swapfuturerK   rJ   )
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   rL   isUnifiedMarginisUnifiedAccountsubTypes                   r   get_url_by_market_typezbybit.get_url_by_market_type   s     %.<		Hit$[[((F"8,6M&>DD==fdFSSLD& ,,T\?KKM ..vxR_``M*f4M&. 	3 1133333333G"nnWa??O#~~gq%@@ 5_ 5=M 5-(0-(4 3-(0&..dh&6&6"&"A"A&&RXZb"c"c-(1 -(2##C((
r   c                 6    |                      |g d          }|S )N)r   r   r   r   unifiedMargin)omit)r   r   s     r   clean_paramszbybit.clean_params   s!    6#b#b#bccr   r   sideamountpricec           	        K   |                                   d{V  |                     ||||||d          }| j        d         d         d         d         }|                     |           d{V  t	          |                                           }	d|	|gt	          |                                           t	          | j        d                   d	d
}
|                     ||	|
|	d           d{V S )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>`
        NTrS   r"   rR   rP   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_wszbybit.create_order_ws   s#     @ !!!!!!!!!00tVUTZ\`aait$Y/8$$$$$$$$$))**	  %((9(9(;(;$<$<&)$,|*D&E&E 

 

 ZZYDIIIIIIIIIr   idc           	        K   |                                   d{V  |                     |||||||          }| j        d         d         d         d         }	|                     |	           d{V  t	          |                                           }
d|
|gt	          |                                           t	          | j        d                   dd	}|                     |	|
||
d
           d{V S )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>`
        NrS   r"   rR   rP   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_wszbybit.edit_order_ws  s!     4 !!!!!!!!!..r64vuV\]]it$Y/8$$$$$$$$$))**	 %((9(9(;(;$<$<&)$,|*D&E&E 

 

 ZZYDIIIIIIIIIr   c                    K   |                                   d{V  |t          | j        dz             |                     |||          }| j        d         d         d         d         }|                     |           d{V  t          |                                           }d|v r|d= d||gt          |                                           t          | j	        d	                   d
d}| 
                    ||||d           d{V S )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>`
        Nz+ cancelOrderWs() requires a symbol argumentrS   r"   rR   rP   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_wszbybit.cancel_order_wsA  sF      !!!!!!!!!>#DG.[$[\\\00VVDDit$Y/8$$$$$$$$$))**	L((]+  %((9(9(;(;$<$<&)$,|*D&E&E 

 

 ZZYDIIIIIIIIIr   c                   K   |                                   d{V  |                     |          }|d         }d|z   }|                     |dd|           d{V }|                     |          }|                     | j        di           }|                     |dd          }|d         s|dk    rt          | j        d	z             |d
|d         z   z  }|g}| 	                    ||g||           d{V S )a&  
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://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:Fr8   rV   rW   rH   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_tickerzbybit.watch_tickere  s2      !!!!!!!!!V$$!&(//}fUUUUUUUU""6**//$,rBB  &)<<f~ 	i%9"4"4TW'gghhhvd|##&&s[M66JJJJJJJJJr   symbolsc                   K   |                                   d{V  |                     |dd          }g }|                     |d         dd|           d{V }|                     |          }|                     | j        di           }|                     |dd          }|                     |          }g }t          dt          |                    D ]C}	||	         }
|
                    |dz   |
z              |
                    d||	         z              D|                     ||||           d{V }| j        ri }|||d	         <   |S |                     | j        d	|          S )
a6  
        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   r9   rV   rW   r   r   r   )r   market_symbolsr   r   r   r}   r   
market_idsrangelenappendr   
newUpdatesfilter_by_arrayrW   )r   r   r   messageHashesr   r}   r   	marketIdsr   imarketIdtickerresults                r   watch_tickerszbybit.watch_tickers~  s      !!!!!!!!!%%gtU;;//
E>SYZZZZZZZZ""6**//$,CC  &)<<OOG,,	q#i..)) 	9 	9A |HMM%#+0111  WQZ!78888((mVVLLLLLLLL? 	F'-F6(#$M##DL(GDDDr   c           	        K   |                                   d{V  |                     |dd          }|                     | j        di           }|                     |dd          }g }g }|                     |          }g }t          dt          |                    D ]]}	||	         }
||	         }|                    |dz   |
z              |                    d|z              |                    d	|z              ^| 	                    |d         dd|           d{V }| 
                    |d
|||||           d{V S )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>`
        NFr9   rV   rW   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_tickerszbybit.un_watch_tickers  s{      !!!!!!!!!%%gtU;;//$,CC  &)<<OOG,,	q#i..)) 	A 	AA |HQZFMM%#+0111##I$6777  !6!?@@@@//
E>SYZZZZZZZZ))#x-Qacikqrrrrrrrrrr   c                 t   K   |                                   d{V  |                     |g|           d{V S )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_tickerzbybit.un_watch_ticker  sV       !!!!!!!!!**F8V<<<<<<<<<r   clientc                 d   |                      |dd          }|                      |dd          }|                     |di           }|                      |d          d u}|rdnd}d }d }	|dk    r|                     |          }	|	d	         }n|d
k    r|                    d          }
t	          |
          }|                      |
|dz
            }|                     |d d |          }|d	         }|                     | j        |i           }|                     |di           }|                     ||          }|                     |          }	|                     |d          }||	d<   | 	                    |          |	d<   |	| j        |<   d|z   }|
                    | j        |         |           d S )Nr    r   datausdIndexPricerH   rN   snapshotr   deltar   r   infots	timestampdatetimer   )r   	safe_dictparse_tickersplitr   safe_marketrW   extendr   iso8601resolve)r   r   messager   
updateTyper   r   r   r   parsed
topicPartstopicLengthr   r   r   	rawTickermergedr   r   s                      r   handle_tickerzbybit.handle_ticker  s   f   '266%%gvr::
~~gvr22!!$88D/vvZ*$$&&t,,FH%FF7""S))Jj//K''
K!ODDH%%hdDAAFH%F^^DL&"==Fvvr::I[[D11F&&v..F%%gt44	'{!\\)44z%V&(t|F+[99999r   c                 R  K   |                                   d{V  |                     |dd          }g }|                     |d         dd|           d{V }|                     |          }|                     |          }g }t          dt          |                    D ]B}||         }d|z   }	|                    |	           |                    d||         z              C|                     ||||           d{V }
| j	        r|
S | 
                    | j        d|          S )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)r   r   r   r   r   r   r   r   r   r   r   s              r   watch_bids_askszbybit.watch_bids_asksV  sY      !!!!!!!!!%%gtU;;//
E?TZ[[[[[[[[""6**OOG,,	q#i..)) 	9 	9A |H"X-EMM%     WQZ!78888((mVVLLLLLLLL? 	M##DM8WEEEr   c                 V   |                      |d          }|                     |                     |d                   d          }|                     |                     |d                   d          }|                     |dg           }|                     |dg           }|                     |d         ||                     |          |                     |d          |                     |d          |                     |d          |                     |d          |d|          S )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_askzbybit.parse_ws_bid_askq  s   %%i==	||DNN9V+<==qAA||DNN9V+<==qAA..q"--..q"--X&"Y//##GQ//))'155##GQ//))'155	!
 	!
 	 	 		r   r_   	timeframesincelimitc                 n   K   d|d<   |                      ||gg|||           d{V }||         |         S )a  
        watches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://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
        r3   callerMethodNameN)watch_ohlcv_for_symbols)r   r   r  r  r  r   r   s          r   watch_ohlcvzbybit.watch_ohlcv  sW       &2!"33fi5H4I5RWY_````````f~i((r   symbolsAndTimeframesc                 h  K   |                                   d{V  |                     |d          }|                     |dddd          }|d         }|                     |dd|           d{V }g }	g }
t	          dt          |                    D ]}||         }|                     |d          }|                     |          }|d         }|                     |d          }|                     | j        ||          }|		                    d|z   d	z   |d
         z              |
	                    d|z   dz   |z              | 
                    ||
|	|           d{V \  }}}| j        r|                    ||          }|                     |||dd          }|                     |||          S )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   FTr4   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   r!  r  r  r   r   marketSymbolsfirstSymbolr   	rawHashesr   r   r   symbolStringr   unfiedTimeframetimeframeIdr   r  storedfiltereds                        r   r  zbybit.watch_ohlcv_for_symbols  s      !!!!!!!!!223GKK++GT5$MM#A&//UDZ\bcccccccc	q#23344 	T 	TA'*D++D!44L[[..F!(+L"..tQ77O**4?O_]]KX3c9F4LHIII  \!9D!@?!RSSSS*.*;*;CPY[a*b*b$b$b$b$b$b$b!	6? 	3OOFE22E--feUAtLL''	8DDDr   c           
        K   |                                   d{V  |                     |d          }|                     |dddd          }|d         }|                     |dd|           d{V }g }g }g }	t	          dt          |                    D ]}
||
         }|                     |d          }|                     |          }|d         }|                     |d          }|                     | j        ||          }|	                    d|z   d	z   |d
         z              |	                    d|z   dz   |z              |		                    d|z   dz   |z              d|i}| 
                    |d||	||||           d{V S )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   FTr4   r   r   r#  r   r   r$  r%  zunsubscribe::ohlcv::r!  ohlcv)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/  subExtensions                    r   un_watch_ohlcv_for_symbolsz bybit.un_watch_ohlcv_for_symbols  s      !!!!!!!!!223GKK++GT5$MM#A&//UDZ\bcccccccc	q#23344 		a 		aA'*D++D!44L[[..F!(+L"..tQ77O**4?O_]]KX3c9F4LHIII##I$<t$Co$UVVV  !7,!F!MP_!_````"$8
 ))#wP`bkms  vB  C  C  C  C  C  C  C  C  	Cr   c                 N   K   d|d<   |                      ||gg|           d{V S )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
        r3   r  N)r5  )r   r   r  r   s       r   un_watch_ohlcvzbybit.un_watch_ohlcv  sC       &2!"44vy6I5JFSSSSSSSSSr   c                    |                      |di           }|                     |d          }|                    d          }t          |          }|                     |d          }|                     |          }|                     ||dz
            }	|j                            d          dk    }
|
rdnd}|                     |	d d |          }|d         }|                      | j        |          }|
i | j        |<   |                      ||          9| 	                    | j
        d	d
          }t          |          | j        |         |<   | j        |         |         }t          dt          |                    D ]3}|                     ||         |          }|                    |           4d|z   dz   |z   }|||g}|                    ||           d S )Nr   r   r   r   rH   rN   r   
OHLCVLimit  r   r$  r%  )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  r0  r   r   r   resolveDatas                        r   handle_ohlcvzbybit.handle_ohlcv  s   . w33  '22[[%%
*oo&&z155''44	##Ja@@((2-%5VV:
!!(D$
CC! OODK@@$"$DK??,i88@%%dlL$GGE-B5-I-IDK	*V$Y/q#d))$$ 	" 	"A((a&99FMM&!!!!&(4/);y&1{K00000r   c           	         |d         rdnd}|                      |d          |                     |d          |                     |d          |                     |d          |                     |d          |                     ||          gS )	NrI   turnovervolumestartopenhighlowclose)r   r  )r   r3  r   volumeIndexs       r   r?  zbybit.parse_ws_ohlcv  s      &,I%6EjjXeW--UF++UF++UE**UG,,UK00
 	
r   c                 B   K   |                      |g||           d{V S )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_bookzbybit.watch_order_book2  s4       66xOOOOOOOOOr   c                   K   |                                   d{V  t          |          }|dk    rt          | j        dz             |                     |          }|                     |d         dd|           d{V }|                     |          }|                     |d                   }|d}|d         rd}nxg d	d
dgg d	d}|                     ||d         d          }| 	                    ||          s9t          | j        dz   |d         z   dz   |                     |          z             g }	g }
t          dt          |                    D ]f}||         }|                     |          }dt          |          z   dz   |z   }|	                    |           d|z   }|
                    |           g|                     ||
|	|           d{V }|                                S )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 symbolsFr5   2   rJ   d   )r   rQ     r;     )rH   rJ   defaultr   rU  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   rN  z"bybit.watch_order_book_for_symbols?  so      !!!!!!!!!GA#DG.q$qrrr%%g..//
ECSU[\\\\\\\\""6**WQZ((=Eh  +**s)--- F
 "--ffVniPPN==77 ` +N!NQWX^Q_!_  cC  "C  FJ  FO  FO  P^  F_  F_  "_  `  `  `q#g,,'' 	. 	.AQZF~~f--H 3u::-3h>EMM%   &/K  ----++COOOOOOOO	   r   c           	        K   |                                   d{V  |                     |dd          }d}|                     |d          }||                     |d          }n'|                     |d                   }|d         rdnd}|t          |          z  }g }g }g }t          dt          |                    D ]t}	||	         }
|                     |
          }|d	         }|d
z   |z   }|                    d|
z              |                    d|
z              |                    |           u| 	                    |d         dd|           d{V }| 
                    |d|||||           d{V S )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
        NFrV  r  r   rH   rQ  i  r   r   zunsubscribe:orderbook:rW  r5   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_symbolsz%bybit.un_watch_order_book_for_symbolsk  s      !!!!!!!!!%%gtU;;!!&'22YYvw//FF++gaj11K%f-6BB3E3u::q#g,,'' 	! 	!AQZF[[((Fd|HcMH,E  !9F!BCCC##L6$9:::MM%    //
ECSU[\\\\\\\\))#{G]Tdflntuuuuuuuuur   c                 t   K   |                                   d{V  |                     |g|           d{V S )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   rb  r   s      r   un_watch_order_bookzbybit.un_watch_order_book  sV       !!!!!!!!!996(FKKKKKKKKKr   c                 t   |                      |d          }|                    d          d         }|j                            d          dk    }|                      |d          }|dk    }|                     |di           }|                      |d	          }	|rdnd
}
|                     |	d d |
          }|d         }|                     |d          }|| j        vr|                                 | j        |<   | j        |         }||d<   |r/| 	                    |||dd          }|
                    |           n|                     |dg           }|                     |dg           }|                     |d         |           |                     |d         |           ||d<   |                     |          |d<   d|z   }|| j        |<   |                    ||           |dk    rM|                     | j        |         |          }i }|||<   || j        |<   |                    |d|z              d S d S )Nr   r   r   rH   r   r   r   r   srN   r   r   bar  r  r   r   rW  rl   r  )r   r   r   r=  r   r   r   
orderbooks
order_bookparse_order_bookresetr  handle_deltasr   r   r  r  )r   r   r   r   r  r   r   
isSnapshotr   r   r@  r   r   r   r  r   r  r  r   bidasknewBidsAskss                        r   handle_order_bookzbybit.handle_order_book  sX   D   '22C  #((A-00j(
~~gvr22##D#..%5VV:
!!(D$
CC!%%gt44	$/))&*oo&7&7DOF#OF+	$	( 		<,,T69c3OOHOOH%%%%>>$R00D>>$R00Dy0$777y0$777%.Ik"$(LL$;$;Ij!'&0"+y+...C<<**4?6+BFKKF "K"(K$*DM&!NN;	F(:;;;;; <r   c                 ^    |                      |dd          }|                    |           d S )Nr   r   )parse_bid_ask
storeArray)r   booksider   bidAsks       r   handle_deltazbybit.handle_delta  s3    ##E1a00F#####r   c                 ~    t          dt          |                    D ]}|                     |||                    d S )Nr   )r   r   rw  )r   ru  deltasr   s       r   rm  zbybit.handle_deltas  sH    q#f++&& 	3 	3Ahq	2222	3 	3r   c                 D   K   |                      |g|||           d{V S )a4  
        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_tradeszbybit.watch_trades  s6       22F8UE6RRRRRRRRRr   c                 $  K   |                                   d{V  |                     |          }t          |          }|dk    rt          | j        dz             |                     |          }|                     |d         dd|           d{V }g }g }t          dt          |                    D ]Y}	||	         }
|                     |
          }d|d         z   }|	                    |           d|
z   }|	                    |           Z| 
                    ||||           d{V }| j        rB|                     |d          }|                     |d	          }|                    ||          }|                     |||d
d          S )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   r'  r(  )r   r   r  r  r   r\  r   r   r   r   r   r   r   r   tradesfirsttradeSymbols                    r   r{  zbybit.watch_trades_for_symbols  s      !!!!!!!!!%%g..GA#DG.n$nooo""6**//
E=RXYYYYYYYYq#g,,'' 	. 	.AQZF[[((F"VD\1EMM%   "V+K  ----((mVVLLLLLLLL? 	8OOFA..E**5(;;KOOK77E))&%TRRRr   c           	        K   |                                   d{V  |                     |ddd          }|                     |d         dd|           d{V }g }g }g }t          dt	          |                    D ]q}||         }|                     |          }	d|	d         z   }
|                    |
           d|z   }|                    |           |                    d	|z              r|                     |d
|||||           d{V S )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   rD   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_symbolsz!bybit.un_watch_trades_for_symbols  sN      !!!!!!!!!%%gtUDAA//
EC\^deeeeeeeeq#g,,'' 	7 	7AQZF[[((F"VD\1EMM%   .7K  ---##Hv$56666))#x-Qacikqrrrrrrrrrr   c                 t   K   |                                   d{V  |                     |g|           d{V S )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   r  r   s      r   un_watch_tradeszbybit.un_watch_trades4  sV       !!!!!!!!!55vhGGGGGGGGGr   c                    |                      |di           }|                     |d          }|}|                    d          }|j                            d          dk    }|rdnd}|                     |d          }	|                     |	d d |          }
|
d         }|                      | j        |          }|5|                     | j        d	d
          }t          |          }|| j        |<   t          dt          |                    D ]3}|                     ||         |
          }|                    |           4d|z   }|                    ||           d S )Nr   r   r   rH   r   rN   r   r   tradesLimitr;  r  )r   r   r   r   r=  r   r  r   r}   r   r   r   parse_ws_trader   r   )r   r   r   r   r   r  partsr   r@  r   r   r   r0  r  jr   r   s                    r   handle_tradeszbybit.handle_tradesA  s_   ( w33  '22C  ((A- &7VVZ
##E1--!!(D$
CC!f55>%%dlM4HHE&&F"(DKq#f++&& 	" 	"A((F;;FMM&!!!!#f,v{+++++r   c                 Z   |                      |g d          }d|v }|rdnd}||d         }|                     |d          }|                     ||d |          }|d         }|                     |dd	          }|                     |d
          }	d }
|                     |d          }|	|rdnd}	n|}
|                     |d          }|                     |dd          }|                     |d          }|                     ||||                     |          ||d |	|
||d d d|          S )N)r   TvBTrN   rH   r   rf  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   rP   r   r   
isContractr@  r   r   r   r   r  r  r   r   orderIds                  r   r  zbybit.parse_ws_tradei  su   @ 77em
#-9ZZ6
J##E3//!!(FD*EE!''sC88	%%eS11OOE3''<)556DD L  ,,##E344""5#.."Y//( 
  
   	r   c                 r    |                     d          dk    rdS |                     d          dk    rdS dS )NrH   r   z
v5/privaterL   rO   )r=  )r   r   s     r   get_private_typezbybit.get_private_type  s?    88Fq  6XXl##q((96r   c                 >  K   d}d}|                                   d{V  ||                     |          }|d|z   z  }|                     |d||           d{V }|                     |           d{V  dddd	}|                     ||                     |                    }	d
}
|                     |ddd
          \  }
}|
rd}	|                     ||g|	g|           d{V }| j        r|	                    ||          }| 
                    ||||d          S )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>`
        r2   myTradesN:T
ticketInfo	executionuser.openapi.perp.traderH   rL   rO   FexecutionFastexecution.fast)r   r   r   r   r   r  handle_option_and_paramsr   r   r'  filter_by_symbol_since_limit)r   r   r  r  r   r   r   r   topicByMarketr   r  r  s               r   watch_my_tradeszbybit.watch_my_trades  s~      ! !!!!!!!!![[((F3<'K//ffMMMMMMMM$$$$$$$$$ "-
 

 t/D/DS/I/IJJ $ = =foWfhm n nv 	%$E(({meWfMMMMMMMM? 	3OOFE22E00tTTTr   c           	        K   d}d}d}|                                   d{V  |t          | j        dz             |                     |d||           d{V }|                     |           d{V  ddd	d
}|                     ||                     |                    }d}	|                     |ddd          \  }	}|	rd}|                     |dg |g|g|g|           d{V S )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>`
        r2   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_tradeszbybit.un_watch_my_trades  s\      !,!!!!!!!!!tw  *B   B  C  C  C//ffMMMMMMMM$$$$$$$$$ "-
 

 t/D/DS/I/IJJ $ = =foWfhm n nv 	%$E))#z2}wiZ_Y`bhiiiiiiiiir   c                    |                      |d          }|dk    }|dk    }|                     |dg           }t          |t                    s|                     |dg           }| j        0|                     | j        dd          }t          |          | _        | j        }i }	|                     dd	g           }
t          d
t          |                    D ]}||         }d }|r|s|                     |          }nG|                      |dd          }|rd}|                     ||
          sX|                     |          }|d         }d|	|<   |                    |           t          |	                                          }t          d
t          |                    D ]#}d||         z   }|                    ||           $d}|                    ||           d S )Nr   r  r  r   r   r  r;  r2   rZ   r   execTyper   r   r   Tz	myTrades:r  )r   r   
isinstancelistr  r   r}   r   handle_optionr   r   r  rY  parse_trader   keysr   )r   r   r   r   rH   r  r   r  r  r   rZ   r   rawTrader   r  r   r  currentMessageHashr   s                      r   handle_my_tradeszbybit.handle_my_trades  s   j   '22$!11w33$%% 	7??4266D= %%dlM4HHE2599DM,,_>OQSTTq#d))$$ 	" 	"AAwHF 	4M 	4,,X66  ++Hj"EE  '&H}}X?? ))(33H%F"GFOMM&!!!!GLLNN##q#d))$$ 	7 	7A!,tAw!6NN6#56666 v{+++++r   c                 *  K   |                                   d{V  d}d}|                     |          s-|                     |          }dd                    |          z   }|                     |d          }|                     |d||           d{V }d|z   }|                     |          }	|                     |           d{V  |                     |	|           | j	        }
| 
                    dd	d          }| 
                    dd
d          }|r8|r6|
4|	                    d	           d{V }|                     ||||d          S dg}|                     ||g||           d{V }| j        r|S |                     |
|||d          S )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   r%  ,r   T	positionsrX   rY   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   cacherX   rY   r   r   newPositionss                   r   watch_positionszbybit.watch_positionsu  s       !!!!!!!!!!}}W%% 	3))'22G'!2!22K&&w22//T66RRRRRRRR!K/S!!$$$$$$$$$  111!%!3!34DF^`d!e!e!%!3!34DF^`d!e!e! 	]&< 	]#]]+CDDDDDDDDH55hPUW[\\\!..s[M66RRRRRRRR? 	 11%%PTUUUr   c                     | j         d S |                     ddd          }|r@d}||j        vr3|                    |           |                     | j        ||           d S d S t                      | _         d S )Nr;   rX   T)r  r  futuresr   spawnload_positions_snapshotr   )r   r   r   rX   r   s        r   r  zbybit.set_positions_cache  s    >%F!%!3!34DF^`d!e!e! 	82K6>11k***

47MMMMM 21 677DNNNr   c                   K   |                      d ddd          |                      d ddd          g}t          j        |  d {V }t                      | _        | j        }t          dt          |                    D ]G}||         }t          dt          |                    D ]}||         }	|                    |	            H||j        v r:|j        |         }
|
	                    |           |	                    |d           d S d S )Nr   rK   )r   r   rI   r   r  )
fetch_positionsasynciogatherr   r  r   r   r   r  r   )r   r   r   fetchFunctionspromisesr  r   r  iir  r   s              r   r  zbybit.load_positions_snapshot  s2        8'L'LMM  9'M'MNN
 !8888888133q#h--(( 	' 	'A IAs9~~.. ' '$R=X&&&&' &.((^K0FNN5!!!NN5*----- )(r   c                    | j         t                      | _         | j         }g }|                     |dg           }t          dt	          |                    D ]}||         }|                     |          }|                     |d          }	|                    |           |	|	dk    r:d|d<   |                    |           d|d<   |                    |           d |d<   |                    |           |                     |d          }
t          dt	          |
                    D ]}|
|         }|	                    d          }|d	         }|	                    d
          }| 
                    |d|d          }|                     |          s|                    ||           |                    |d           d S )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   )r   r   r   r  r  rawPositionsr   rawPositionr  r   r   r   r  symbolsStringr   r  s                   r   handle_positionszbybit.handle_positions  s   P >!577DNw;;q#l++,, 	' 	'A&q/K**;77H##Hf55D )))|trzz $* X&&&#* X&&&#'   X&&&&00GGq#m,,-- 	7 	7A'*K%%d++E!!HM#))#..G,,\8WeTTI==++ 7y+666|[11111r   c           	      \  K   |                                   d{V  d}d}d}|                     |          st          | j        dz             |                     dd||           d{V }|                     |           d{V  dg}|                     |d||g|g||           d{V S )aE  
        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_positionszbybit.un_watch_positions  s      !!!!!!!!!!-}}W%% 	Atw)  A  A  A//dFFKKKKKKKK$$$$$$$$$))#{Gk]U\T]_egmnnnnnnnnnr   c                   K   |                                   d{V  |                     |          }|d         }|                     |dd|           d{V }|                     |          }d}|                     |ddd          \  }}d|z   }|dz   |d	         z   }	|                     ||g|	g|           d{V }
| j        r|
S |                     | j        |g||d
          S )a  
        watch the public liquidations of a trading pair

        https://bybit-exchange.github.io/docs/v5/websocket/public/all-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   allLiquidation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_liquidationszbybit.watch_liquidations  s*      !!!!!!!!!V$$!//?RTZ[[[[[[[[""6**66v?RT\^noo&/vd|+#00{meWfUUUUUUUU? 	"!!11$2CfXuV[]abbbr   c                 .   t          |d         t                    r|                     |dg           }t          dt	          |                    D ]}||         }|                     |d          }|                     |d dd          }|d         }|                     ||          }	| j        0| 	                    | j
        dd          }
t          |
          | _        | j        }|                    |	           |                    |	gd	           |                    |	gd
|z              d S |                     |di           }|                     |d          }|                     |d dd          }|d         }|                     ||          }	| j        0| 	                    | j
        dd          }
t          |
          | _        | j        }|                    |	           |                    |	gd	           |                    |	gd
|z              d S )Nr   r   rf  r   rN   r   liquidationsLimitr;  r  r  )r  r  r  r   r   r   r   parse_ws_liquidationr  r   r}   r   r   r   r   )r   r   r   rawLiquidationsr   rawLiquidationr   r   r   liquidationr  r  s               r   handle_liquidationzbybit.handle_liquidation3  s"   < gfot,, 	E"nnWfbAAO1c/2233 I I!0!3++NC@@))(D"jII)"77OO$, --dl<OQUVVE(25(9(9D%)[)))}n===}.>.GHHHHI I "^^GVR@@N''AAH%%hb*EEFH%F33NFKKK ())$,8KTRR$.u$5$5!%ELL%%%NNK=.999NNK=*:V*CDDDDDr   c                    |                      |dd          }|                     ||dd          }|                     |dd          }|                     ||d         |                     |dd          |                     |d	          |                     |d
d          |                     |dd          d d ||                     |          d
          S )Nr   rf  r   rN   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  zbybit.parse_ws_liquidationn  s    $ %%k8SAA!!(FB
CC'']CHH	$$X&++KEE ,,V^DD''WcBB**;DD"Y//&
 &
   	r   c                   K   |                                   d{V  d}d}||                     |          }|d|z   z  }|                     |d||           d{V }|                     |           d{V  ddgdgdgd	}|                     ||                     |                    }	|                     ||g|	|           d{V }
| j        r|
                    ||          }| 	                    |
|||d          S )
a5  
        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>`
        Nr7   ordersr  Tr  	stopOrderuser.openapi.perp.orderr  )
r   r   r   r   r   r  r   r   r'  r  )r   r   r  r  r   r   r   r   topicsByMarketr   r  s              r   watch_orderszbybit.watch_orders  sT      !!!!!!!!![[((F3<'K//ffMMMMMMMM$$$$$$$$$k*y./ 
  

 1F1Fs1K1KLL(({mVVLLLLLLLL? 	3OOFE22E00tTTTr   c           	        K   |                                   d{V  d}d}d}|t          | j        dz             |                     |d||           d{V }|                     |           d{V  ddgdgd	gd
}|                     ||                     |                    }|                     |dg |g|g||           d{V S )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>`
        Nr7   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_orderszbybit.un_watch_orders  s"      !!!!!!!!!*tw)||}}}//ffMMMMMMMM$$$$$$$$$k*y./ 
  

 1F1Fs1K1KLL))#xk]WIW]_efffffffffr   c                     |                      |d          }|                     |d          }|                     |          }|                    ||           d S )Nr   r   )r   r   parse_orderr   )r   r   r   r   r   r  s         r   handle_order_wszbybit.handle_order_ws  sY    * &&w88~~gv..  &&uk*****r   c                    | j         0|                     | j        dd          }t          |          | _         | j         }|                     |dg           }|                     |di           }|                     |d          }|dk    }|s|                     |d|          }i }	t          dt          |                    D ]?}
|                     ||
                   }|d         }d	|	|<   |	                    |           @t          |	                                          }t          dt          |                    D ]#}
d
||
         z   }|                    ||           $d}|                    ||           d S )NordersLimitr;  r   r   categoryrH   r   r   Tzorders:r  )r  r   r}   r   r   r   r   r   r  r   r  r  r   )r   r   r   r  r  	rawOrdersr  r  r   r   r   r   r   symbolsArrayr  r   s                   r   handle_orderzbybit.handle_order  s   h ;%%dlM4HHE077DKOOGVR88		1b11##E:66V# 	H	8YGGIq#i..)) 		" 		"A%%il33F H%F"GFOMM&!!!!GLLNN++q#l++,, 	7 	7A!*\!_!<NN6#56666v{+++++r   c                   K   |                                   d{V  d}d}d}|                     dd|          \  }}d}|                     dd|          \  }}|                                  d{V }|                     |dd          }|                     |dd          }|                     dd||           d{V }	|                     |	           d{V  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  }|                     |
|                     |	                    g}| 	                    |	|g||           d{V S )ag  
        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)rH   rL   rI   z	:contractz:unifiedrH   z:spotrK   )
r   r   r   r   r   r   r   r   r  r   )r   r   r   r   r   r   rL   r   r   r   r  r   s               r   watch_balancezbybit.watch_balanceT  s      !!!!!!!!! 99.$PVWWf99.$PVWW--////////..!U;;>>'1e<<//dFFKKKKKKKK$$$$$$$$$)
 
  	*)##{*z) 	+'7 	+v~~w&{* 	/v~~w&h&&:-KK;.K//-1F1Fs1K1KLLM&&s[M66JJJJJJJJJr   c           	         | j         i | _         d}|                     |d          }d }g }d }|dk    rnd}|                     |dg           }t          dt          |                    D ]5}	|                     ||	         dg           }
|                     ||
          }6|}|dk    r|                     |di           }t          dt          |                    D ]Z}	|                     |di           }|                     |d	          }|                     ||                     |d
g                     }[|}t          dt          |                    D ]}	|                     ||	         |           ||                     | j         |          
i | j         |<   || j         |         d<   |                     |d          }|| j         |         d<   |                     |          | j         |         d<   | 	                    | j         |                   | j         |<   d|z   }|
                    | j         |         |           d S || j         d<   |                     |d          }|| j         d<   |                     |          | j         d<   | 	                    | j                   | _         d}|
                    | j         |           d S )Nbalancer   r	  rH   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   r  r   r   s                r   handle_balancezbybit.handle_balance  s   ^ <DL11)))G??7FB77D1c$ii(( @ @OODGS"55"//Q??DH??7FB77D1c$ii(( b bq"5500GG"//T__VU[]_=`=`aaDq#k**++ 	; 	;A!!+a.'::::t|W55=(*W%,0DL!&)))'488I1:DL!+.04Y0G0GDL!*-$($5$5dl76K$L$LDL!%/KNN4<0+>>>>>#'DL ))'488I(1DL%'+||I'>'>DL$,,T\::DL$KNN4<55555r   c                    |                                  }|                     |dd          }|                     |          }|                     |g d          |d<   |                     |dd          |d<   |                     |d          |d	<   |7|                     | j        |          
i | j        |<   || j        |         |<   d S || j        |<   d S )
Nrh  r  )availableToWithdrawffreer  r  llockedusedwalletBalancetotal)r  r   safe_currency_coder  r   r   r  )r   r  r  r  
currencyIdcodes         r   r  zbybit.parse_ws_balance>  s    4 ,,..''f==
&&z22,,W6q6q6qrr,,Wc8DD++G_EE"t|[99A,.[).5DL%d+++!(DLr   c                    K   d|                                  |d}|                     ||          }|                     ||||           d {V S )N	subscriber   req_idr   r   r   watch_multiple)r   r   r   r   r   r   r   s          r   r   zbybit.watch_topicse  sf      oo''
 

 ++gv..((mWmTTTTTTTTTr   r   r   r   r   c	           
         K   |                                  }	d|	|d}
|	||||d}|                     |
|          }|                     |||||                     ||                     d {V S )Nunsubscriber%  )r   r   r   r   r   r'  )r   r   r   r   r   r   r   r   r4  r   r   subscriptionr   s                r   r   zbybit.un_watch_topicsn  s      !!
 
 * 0
 
 ++gv..((mWmUYU`U`amo{U|U|}}}}}}}}}r   c                 F  K   |                                   d}|                     |          }|                    |          }|                     |j        |          }||                                 dz   }|                     |          }d}	|	|z   }
|                     |                     |
          |                     | j	                  t          j        d          }d| j        ||gd}|                     ||          }|                     ||||           | d {V S )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   r-  
expiresIntexpirespathr/  	signaturer   r   s                 r   r   zbybit.authenticate  s$     '')))%S!!&&{33(<kJJ **,,u4J++J77G!D'>D		$++d"3"3T[[5M5Mw~_deeIK) G kk'622GJJsK+>>>||||||r   c                    |                      |g d          }	 ||dk    r| j        dz   |                     |          z   }|                     | j        d         ||           |                     |dd          }|                     | j        d         ||           t          |          |                     |d          }|w|su| 	                    |d          }|                     |d	i           }| 	                    |d
          }	|	dk    rt          d|z             t          | j        dz   |z             dS # t          $ rv}
t          |
t                    r*d}|                    |
|           ||j        v r|j        |= n,| 	                    |d          }|                    |
|           Y d }
~
dS d }
~
ww xY w)N)r"  ret_coderetCode0 exactretMsgret_msgbroadsuccessr   r   r/  zAuthentication failed: Fr-  r   T)r  r   rZ  throw_exactly_matched_exception
exceptionsr   throw_broadly_matched_exceptionr   r   r   r   	Exceptionr  rejectr2  )r   r   r   r"  feedbackmsgrG  rE  r   r   errorr   s               r   handle_error_messagezbybit.handle_error_message  s   X !!'+J+J+JKK	DCKK7S=499W+=+==44T_W5MtU]^^^(((IFF44T_W5MsT\]]]#H---oogy99G"7"**7I>>//'9bAA%%gt44<<-.G'.QRRR'#(?@@@5 		 		 		%!455 2-e[111&"666,[9"..w@@e[11144444		s   D!D= =
F=A+F88F=c                    |                      |ddd          }|                     ||          rd S |                     |d          }|dk    s|dk    r|                     ||           d S |                     |d          }||                     ||           d S |                     |d          }|dk    s|dk    r|                     ||           d S 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        | j        d}|                     ||          }| |||           d S t'          |                                          }	t+          dt-          |	                    D ]@}
|	|
         }|                    |	|
                   dk    r||         } |||            d S A|                     |d          }|dk    r|                     ||           d S d S )Nr   r   r   rE  pongeventsubr$  r  kliner  r  r   rP   publicTradedepthr
  r	  r  r  r  r  r  r  r  )rR  r   r   r   r/  r*  r   r   	AUTH_RESP)r   rP  r   handle_pongr   handle_subscription_statusrq  rC  r  r  r  r  r  r  r  r   handle_authenticatehandle_un_subscriber   r  r  r   r   r=  )r   r   r   r   rE  rR  rS  methods
exacMethodr  r   keyr   r   s                 r   handle_messagezbybit.handle_message  s"   ""7GT2>>$$VW55 	F""7I66v5F??VW---F  &11VW---F  '22E>>e{22++FG<<<F
/
T&
 T&
 *	

 d(
 T'
 4-
 T+
 d)
 "4#6
 .
 d3
 $/
 &t'<
 -
  42!
" d5#
$ $ 0/ 0,3/
 
 
2 __We44
!Jvw'''FGLLNN##q#d))$$ 	 	Aq'Czz$q'""a'' vw''' (
 00;$$VW55555 r   c                 0    |                                  ddS )Nry   )r&  r   )r   )r   r   s     r   ry   z
bybit.ping	  s!    oo''
 
 	
r   c                 b    |                      |d|                                           |_        |S )NrR  )r   r   lastPongr   r   r   s      r   rY  zbybit.handle_pong 	  s.    & ++GVT=N=N=P=PQQr   c                 |   |                      |d          }|                     |d          }d}|s|dk    r1|                      |j        |          }|                    d           nTt	          | j        dz   |                     |          z             }|                    ||           ||j        v r|j        |= |S )NrG  r@  r-  r   TrB  )	r   r   r  r   r   r   rZ  rL  r2  )r   r   r   rG  r"  r   r   rO  s           r   r[  zbybit.handle_authenticate6	  s    . //'955  )44% 	6daii__V^[AAFNN4    '#		'8J8J(JKKEMM%---f222(5r   c                     |S N rd  s      r   rZ  z bybit.handle_subscription_statusZ	  s	     r   c                    |                      |d          }t          |j                                                  }t	          dt          |                    D ]}||         }||j        vr|                    d          r|j        |         }|                      |d          }||k    rS|                     |dg           }	|                     |dg           }
t	          dt          |	                    D ]<}|	|         }|
|         }|dk    p|dk    p|d	k    }|                     ||||           =| 	                    |           |S )
Nr&  r   r*  r   r   r   r  r  r  )
r   r  r2  r  r   r   
startswithr  clean_unsubscriptionclean_cache)r   r   r   r   r  r   r   r+  subIdr   r   r  	unsubHashr  	usePrefixs                  r   r\  zbybit.handle_un_subscribek	  sm      (33F(--//00q#d))$$ 	/ 	/Aq'K6#777%%m44 /%3K@((t<<E>> $|_b Q Q#'>>,@RTV#W#W q#m"4"455 U UA -a 0I.q1G!(H!4 l'Z:O lU\`kUkI--fgy)TTTT  ...r   rg  )W__name__
__module____qualname__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  r5  r7  rC  r?  r   rO  rN  rb  rd  rq  rw  rm  r   r|  r{  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r   r  r  r  r   r  r  r   r  r   r  r  r  r   r   r   r	   rP  r`  ry   rY  r[  rZ  r\  __classcell__)r   s   @r   r   r      sH       Z# Z Z Z Z Z Zx   :>^bkm $ $3 $X[ $ $ $ $L   pt|~ 0J 0JC 0Jy 0J	 0J[` 0Jil 0J 0J 0J 0Jd im{  IK *J *Jc *J3 *Ji *Jy *Jbe *Jux *J *J *J *JX <@ "J "J "JS "J "J "J "JH 68 K K KF K K K K2 6:" E E7 E E E E E> 9=R s sg sC s s s s8 9; = =C =s = = = =M:F M: M: M: M:^ 8<B F FW F7 F F F F6   " ?CQUdhqs ) ) ) )3 )^a )x|  ~B  yC ) ) ) )$ aesw  AC !E !E$tCy/ !EZ] !Emp !E !E !E !EF ^`  C  CT$s)_  Cdg  C  C  C  CD BFb T T3 T3 TUX T T T T.16 .1 .1 .1 .1`
 
D 
 
 
 
4 @DB P PS P PS\ P P P P SW_a *! *!$s) *!C *!fo *! *! *! *!X PR !v !vT#Y !vVY !v !v !v !vF =? L L L3 L L L LC< C< C< C< C<J$ $ $3 3 3 <@d[] S S SS S Sbfglbm S S S S OSaenp !S !Sd3i !S !S[^ !Suyz  vA !S !S !S !SF LN s sc sRU s s s s4 9; H HC Hs H H H H&,F &, &, &, &,PB B B BH   37TX\eg $U $UC $Us $URU $Ulpqvlw $U $U $U $UL 6:" j js j j j j jBw,v w, w, w, w,r 8<$]ajl "V "VW "VC "VWZ "Vquv~q "V "V "V "VH
8 
8& 
87 
8 
8 
8 
8. . .(H2 H2 H2T ;?r o o oc o o o o* BFTXac c cs c3 cc chlmxhy c c c c69E 9E 9E 9E 9Ev       D 04$UYbd U U UC Us Uimnsit U U U U> 37r g gC gc g g g g6+f + + + +4n,6 n, n, n, n,` *, /K /K /K /K /K /Kbw6V w6 w6 w6 w6r%) %) %) %)N EG U U U U SU  df ~ ~ ~S ~7 ~[_`c[d ~x|  ~A  yB ~ ~ ~ ~" .0    ,G6 Gt G G G GR:6V :6 :6 :6 :6x
6 
 
 
 
&    ,"& " " " "H    "!& ! ! ! ! ! ! ! !r   r   )&ccxt.async_supportccxt ccxt.async_support.base.ws.cacher   r   r   r   r  r7  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   rh  r   r   <module>r}     s       A  A  A  A  A  A  A  A  A  A  A  A   _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _  _ 4 4 4 4 4 4       * * * * * * 0 0 0 0 0 0 . . . . . . ' ' ' ' ' ' ) ) ) ) ) )x% x% x% x% x%D$ x% x% x% x% x%r   