
    ":hQ                         d dl Zd dlmZmZmZ d dlmZmZm	Z	m
Z
mZmZmZmZmZmZ d dlmZ d dlmZ d dlmZ d dlmZ  G d d	ej0                  j2                        Zy)
    N)
ArrayCacheArrayCacheBySymbolByIdArrayCacheByTimestamp)
AnyBalancesIntOrder	OrderBookStrStringsTickerTickersTrade)Client)List)ExchangeError)ArgumentsRequiredc            
           e Zd Zdef fdZi fdZi fdZd Zi dfdZi dfdZ	i df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efdZdi fdedefdZdi fdedefdZdefdZd9dZdddi fdedededee   fdZdef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Z i fdedefdZ!defdZ"di fdedede#fd Z$i f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'defd$Z(d% Z)d& Z*d' Z+defd(Z,defd)Z-defd*Z.dddi fde/dededee0   fd+Z1d, Z2d9d-Z3defd.Z4dddi fde/dededee   fd/Z5defd0Z6d9d1Z7i fde8fd2Z9defd3Z:defd4Z;defd5Z<defd6Z=defd7Z>defd8Z? xZ@S ):kucoin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iddddddidd| j                  id       S )!NwsTcreateOrderWsFeditOrderWsfetchOpenOrdersWsfetchOrderWscancelOrderWscancelOrdersWscancelAllOrdersWswatchBidsAskswatchOrderBookwatchOrderswatchMyTradeswatchTickerswatchTickerwatchTradeswatchTradesForSymbolswatchOrderBookForSymbols)watchBalance
watchOHLCV  namezmarket/snapshot      /market/level2)snapshotDelaysnapshotMaxRetriesmethodr2   /spotMarket/tradeOrders)tradesLimitr%   r!   r#   ping)hasoptions	streaming)deep_extendsuperr   describer5   )self	__class__s    I/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/pro/kucoin.pyr;   zkucoin.describe   sE   fd < >d u $U	
    !% $U   !$ t    t t  (!" +D#$ !%"',  $-  &'*+.# 7"$ 			I*A
 * *	    c                   K   |rdnd}| j                  | j                  di       }| j                  ||      }|
| d {   S | j                  | j                  ||      ||<   || j                  d<   ||   }| d {   S 7 B7 w)Nprivatepublicurls)
safe_valuer7   spawnnegotiate_helper)r<   privateChannelparams	connectIdrC   spawanedfutures          r>   	negotiatezkucoin.negotiate>   s     !/IX	t||VR8??43!>! **T%:%:NFSY#Vi| " s"   =BB =B=B>BBc                   K   d }|rdnd}	 |r| j                  |       d {   }n| j                  |       d {   }| j                  |di       }| j                  |dg       }| j                  |d      }| j                  |d      }| j	                  |d      }	| j	                  |d      }
|	d	z   | j                  |
||d
      z   }| j                  |      }||_        |S 7 7 # t        $ rJ}| j                  | j                  d   |      }|j                  |       | j                  d   |= Y d }~y d }~ww xY ww)NrA   rB   datainstanceServersr   pingIntervalendpointtoken?)rR   rG   rI   rC   )privatePostBulletPrivatepublicPostBulletPublicrD   safe_integersafe_string	urlencodeclient	keepAlive	Exceptionr7   reject)r<   rG   rH   responserI   rN   rO   firstInstanceServerrP   rQ   rR   resultrY   erK   s                  r>   rF   zkucoin.negotiate_helperL   sN    !/IX	'	0!%!>!>v!FF& "&!<!<V!DD??8VR8D"ood4ErJO"&///1"E,,-@.QL''(;ZHH$$T73E^dnn"0&6 ' F
 [[(F+FMC G& E  	0__T\\&%99EFMM!V$Y/		0sP   	D>C( C$C( C&B&C( #D>$C( &C( (	D;1A D61D>6D;;D>c                 ~    | j                  | j                  | j                  dd      d      }|| j                  d<   |S )N	requestIdr      )sumrV   r7   )r<   rb   s     r>   
request_idzkucoin.request_idy   s9    HHT..t||[!LaP	$-[!r?   Nc                   K   t        | j                               }|d|dd}| j                  ||      }| j                  |      }	||	j                  vr||	j                  |<   | j                  |||||       d {   S 7 w)N	subscribeTidtypetopicr]   )strre   extendrY   subscriptionswatch)
r<   urlmessageHashsubscriptionHashrH   subscriptionrb   requestmessagerY   s
             r>   rg   zkucoin.subscribe~   s     )*	%	
 ++gv.S! F$8$88.>F  +ZZ[';K\ZZZZs   A9B;B <Bc                 H  K   t        | j                               }|d|dd}| j                  ||      }	| j                  |      }
t	        dt        |            D ]%  }||   }||
j                  vs||
j                  |<   ' | j                  |||	||       d {   S 7 w)Nrg   Trh   r   rl   re   rm   rY   rangelenrn   watch_multipler<   rp   messageHashesrk   subscriptionHashesrH   rs   rb   rt   ru   rY   irr   s                r>   subscribe_multiplezkucoin.subscribe_multiple   s     )*		
 ++gv.S!q#012 	CA1!4$(<(<<2B$$Y/	C ((mWFXZfggggs   A/B"2)B"B B"rs   c                 V  K   t        | j                               }|d|dd}| j                  ||      }	||||<   | j                  |      }
t	        dt        |            D ]%  }||   }||
j                  vs||
j                  |<   ' | j                  |||	||       d {   S 7 w)NunsubscribeTrh   r   rw   r{   s                r>   un_subscribe_multiplezkucoin.un_subscribe_multiple   s     )*	!	
 ++gv.#&/L#S!q#012 	CA1!4$(<(<<2B$$Y/	C ((mWFXZfggggs   A6B)9)B)"B'#B)symbolc                 *  K   | j                          d{    | j                  |      }|d   }| j                  d       d{   }| j                  |ddd      \  }}|dz   |d   z   }d	|z   }| j	                  ||||       d{   S 7 v7 I7 w)
a  
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/market-snapshot

        :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   Fr%   r2   z/market/snapshot:ri   ticker:)load_marketsmarketrL   handle_option_and_paramsrg   )	r<   r   rH   r   rp   r2   queryrk   rq   s	            r>   watch_tickerzkucoin.watch_ticker   s      !!!V$!NN5))55fmXWijvd|+&(^^CeUCCC 	" * Ds4   BB.BBABB	BBBsymbolsc                   K   | j                          d{    | j                  |      }d}d}| j                  |ddd      \  }}g }g }|^t        dt	        |            D ]F  }||   }|j                  d|z          | j                  |      }	|j                  |dz   |	d	   z          H | j                  d
       d{   }
d}|/|dz   }| j                  |
|||       d{   }| j                  r_|S | j                  |      }|dz   dj                  |      z   }| j                  |
||||       d{   }| j                  ri }|||d   <   |S | j                  | j                  d|      S 7 [7 7 7 @w)ab  

        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/ticker

        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list
        :param str[] symbols: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.method]: either '/market/snapshot' or '/market/ticker' default is '/market/ticker'
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        Ntickersr$   r2   z/market/tickerr   r   r   ri   Fz:all,r   )r   market_symbolsr   rx   ry   appendr   rL   rg   
newUpdates
market_idsjoinr   filter_by_arrayr   )r<   r   rH   rq   r2   r|   topicsr~   r   r   rp   r   allTopic	marketIdssymbolsTopicnewDicts                   r>   watch_tickerszkucoin.watch_tickers   s     !!!%%g.66v~xYij1c'l+ ; $$Y%78V,fslVD\9:	;
 NN5))?H NN3XvNNG0I!C<#((9*==L 33CV\^deeG "-4)*##DLL(GDD9 	" * O fsG   E:E1B(E:?E4 $E:$E6%AE:7E88:E:4E:6E:8E:rY   c                    | j                  |d      }d }|R|j                  d      }| j                  |d      }d }|dk(  r| j                  |d      }n|}| j                  ||d      }| j                  |di       }| j                  |d|      }	| j	                  |	|      }
|
d   }|
| j
                  |<   d	|z   }|j                  |
|       i }|
||<   |j                  |d
       y )Nrk   r   rc   allsubject-rN   r   r   r   )rW   splitsafe_marketrD   parse_tickerr   resolve)r<   rY   ru   rk   r   partsfirstmarketIdrN   	rawTickertickerr   rq   
allTickerss                 r>   handle_tickerzkucoin.handle_ticker   s    n   '2KK$E$$UA.EH~++GY? %%h<Fw3OOD&$7	""9f5!%V&(v{+
#
6z9-r?   c                    K   | j                  dd||       d{   }| j                  ri }|||d   <   |S | j                  | j                  d|      S 7 9w)a  

        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/level1-bbo-market-data

        watches best bid & ask for symbols
        :param str[] symbols: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        r    z/spotMarket/level1:Nr   )watch_multi_helperr   r   bidsasks)r<   r   rH   r   r   s        r>   watch_bids_askszkucoin.watch_bids_asks8  sc      ..@UW^`fgg??G(.GF8$%N##DMM8WEE hs   AA:AchannelNamec                 x  K   | j                          d {    | j                  |d ddd      }t        |      }|dkD  rt        | j                  dz   |z   dz         g }t        dt        |            D ]/  }||   }| j                  |      }	|j                  d|	d   z          1 | j                  d       d {   }
| j                  |      }d	j                  |      }t        | j                               }|d
||z   dd}| j                  ||      }| j                  |
|||       d {   S 7 7 z7 	w)NFTd    z#() accepts a maximum of 100 symbolsr   bidask@r   r   rg   rh   )r   r   ry   r   ri   rx   r   r   rL   r   r   rl   re   rm   rz   )r<   
methodNamer   r   rH   lengthr|   r~   r   r   rp   r   joinedrb   rt   ru   s                   r>   r   zkucoin.watch_multi_helperI  sB    !!!%%gtUD%HWC<#DGGcMJ$>Af$fggq#g,' 	?AQZF[[(F  VH-=!=>	? NN5))OOG,	)$)*	 6)	
 ++gv.((mWmTTT+ 	" * Us5   D:D3B$D:;D6<A2D:.D8/D:6D:8D:c                 |    | j                  |      }|d   }|| j                  |<   d|z   }|j                  ||       y )Nr   r   )parse_ws_bid_askr   r   )r<   rY   ru   parsedTickerr   rq   s         r>   handle_bid_askzkucoin.handle_bid_aska  sD     ,,W5h' ,f&(|[1r?   c                    | j                  |d      }|j                  d      }|d   }| j                  ||      }| j                  |d      }| j                  |di       }| j	                  |dg       }| j	                  |dg       }	| j                  |d      }
| j                  ||
| j                  |
      | j                  |d	      | j                  |d      | j                  |	d	      | j                  |	d      |d
|      S )Nrk   r   rc   r   rN   asksbids	timestampr   )r   r   datetimeask	askVolumebid	bidVolumeinfo)	rW   r   r   	safe_dict	safe_listrV   safe_tickeriso8601safe_number)r<   r   r   rk   r   r   r   rN   r   r   r   s              r>   r   zkucoin.parse_ws_bid_askv  s	     1C 8!!(F3!!&(3~~ffb1nnT62.nnT62.%%dK8	"Y/##C+))#q1##C+))#q1	!
 	 		r?   1msincelimitc                   K   | j                          d{    | j                  d       d{   }| j                  |      }|d   }| j                  | j                  ||      }d|d   z   dz   |z   }	d|z   dz   |z   }
| j                  ||
|	|       d{   }| j                  r|j                  ||      }| j                  |||d	d
      S 7 7 7 ;w)a  
        watches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/klines

        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in 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
        NFr   z/market/candles:ri   _candles:r   r   T)	r   rL   r   rW   
timeframesrg   r   getLimitfilter_by_since_limit)r<   r   	timeframer   r   rH   rp   r   periodrk   rq   ohlcvs               r>   watch_ohlcvzkucoin.watch_ohlcv  s      !!!NN5))V$!!!$//9iH"VD\1C7&@ 6)C/);nnS+ufEE??NN651E))%q$GG 	") Fs2   CCCCA'CC8CCCc                    | j                  |di       }| j                  |d      }| j                  |dg       }| j                  |d      }|j                  d      }| j                  |d      }| j                  |      }	| j	                  |      }
|
d   }d|z   dz   |	z   }| j                  | j
                  |i       | j
                  |<   | j                  | j
                  |   |	      }|:| j                  | j                  d	d
      }t        |      }|| j
                  |   |	<   | j                  ||
      }|j                  |       |j                  ||       y )NrN   r   candlesrk   r   rc   r   r   
OHLCVLimitr+   )rD   rW   r   find_timeframer   ohlcvsrV   r7   r   parse_ohlcvr   r   )r<   rY   ru   rN   r   r   rk   r   intervalr   r   r   rq   storedr   r   s                   r>   handle_ohlcvzkucoin.handle_ohlcv  sH   * w3##D(3//$	26  '2C ##E1-''1	!!(+! 6)C/);"oodkk62FFV!4i@>%%dllL$GE*51F-3DKK	*  &1ev{+r?   c                 H   K   | j                  |g|||       d{   S 7 w)a>  
        get the list of most recent trades for a particular symbol

        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/match-execution-data

        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        N)watch_trades_for_symbols)r<   r   r   r   rH   s        r>   watch_tradeszkucoin.watch_trades  s'      22F8UE6RRRRs   " "c                   K   t        |      }|dk(  rt        | j                  dz         | j                          d{    | j	                  |      }| j                  |      }| j                  d       d{   }g }g }	ddj                  |      z   }
t        dt        |            D ]4  }||   }|j                  d|z          ||   }|	j                  d|z          6 | j                  |||
|	|       d{   }| j                  r6| j                  |d      }| j                  |d      }|j                  ||      }| j                  |||d	d
      S 7 7 7 `w)a  
        get the list of most recent trades for a particular symbol

        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/match-execution-data

        :param str[] symbols:
        :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>`
        r   z> watchTradesForSymbols() requires a non-empty array of symbolsNF/market/match:r   trades:r   r   T)ry   r   ri   r   r   r   rL   r   rx   r   r   r   rD   rW   r   r   )r<   r   r   r   rH   symbolsLengthr   rp   r|   r}   rk   r~   r   r   tradesr   tradeSymbols                    r>   r   zkucoin.watch_trades_for_symbols  se     GA#DGG.n$noo!!!%%g.OOG,	NN5)) 388I#66q#g,' 	CAQZF  V!34 |H%%&6&AB		C
 ..sM5J\^dee??OOFA.E**5(;KOOK7E))&%TRR# 	" * fs5   <EE:E9E:B E:E;AEEEc                   K   | j                          d{    | j                  |dd      }| j                  |      }| j                  d       d{   }g }g }ddj	                  |      z   }t        dt        |            D ]/  }||   }	|j                  d|	z          |j                  d|	z          1 ||dd	|d
}
| j                  ||||||
       d{   S 7 7 7 w)a^  
        unWatches trades stream

        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/match-execution-data

        :param str symbols:
        :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>`
        NFr   r   r   zunsubscribe:trades:r   r   T)r|   subMessageHashesrk   r   r   )	r   r   r   rL   r   rx   ry   r   r   )r<   r   rH   r   rp   r|   r}   rk   r~   r   rs   s              r>   un_watch_trades_for_symbolsz"kucoin.un_watch_trades_for_symbols  s     !!!%%gtU;OOG,	NN5)) 388I#66q#g,' 	:AQZF  !6!?@%%i&&89	:
 + 2
 //]E=Z`bnooo% 	" * ps4   C#C<C#CBC#C!C#C#!C#c                 D   K   | j                  |g|       d{   S 7 w)a  
        unWatches trades stream

        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/match-execution-data

        :param str symbol: unified symbol of the market to fetch trades for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        N)r   r<   r   rH   s      r>   un_watch_tradeszkucoin.un_watch_trades  s#      55vhGGGG     c                 P   | j                  |di       }| j                  |      }|d   }d|z   }| j                  | j                  |      }|7| j                  | j                  dd      }t        |      }|| j                  |<   |j                  |       |j                  ||       y )NrN   r   r   r4   r+   )rD   parse_trader   rV   r7   r   r   r   )	r<   rY   ru   rN   trader   rq   r   r   s	            r>   handle_tradezkucoin.handle_trade(  s    ( w3  &x&(f5>%%dllM4HE&F"(DKKev{+r?   c                 F   K   | j                  |g||       d{   S 7 w)a  

        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/level1-bbo-market-data
        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/level2-market-data
        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/level2-5-best-ask-bid-orders
        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/level2-50-best-ask-bid-orders

        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :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
        :param str [params.method]: either '/market/level2' or '/spotMarket/level2Depth5' or '/spotMarket/level2Depth50' default is '/market/level2'
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        N)watch_order_book_for_symbols)r<   r   r   rH   s       r>   watch_order_bookzkucoin.watch_order_bookH  s%     < 66xOOOOs   !!c                 D   K   | j                  |g|       d{   S 7 w)a  

        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/level1-bbo-market-data
        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/level2-market-data
        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/level2-5-best-ask-bid-orders
        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/level2-50-best-ask-bid-orders

        unWatches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :param str symbol: unified symbol of the market to fetch the order book for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.method]: either '/market/level2' or '/spotMarket/level2Depth5' or '/spotMarket/level2Depth50' default is '/market/level2'
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        N)un_watch_order_book_for_symbolsr   s      r>   un_watch_order_bookzkucoin.un_watch_order_bookh  s#      996(FKKKKr   c                 *  K   t        |      }|dk(  rt        | j                  dz         |,|dk7  r'|dk7  r"|dk7  r|dk7  rt        | j                  dz         | j	                          d{    | j                  |      }| j                  |      }| j                  d	       d{   }d}| j                  |d
dd      \  }}|dk(  s|dk(  rdt        |      z   }|dz   dj                  |      z   }g }	g }
t        dt        |            D ]7  }||   }|	j                  d|z          ||   }|
j                  |dz   |z          9 i }|dk(  r| j                  ||d}| j                  ||	||
||       d{   }|j                         S 7  7 7 w)a  

        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/level1-bbo-market-data
        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/level2-market-data
        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/level2-5-best-ask-bid-orders
        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/level2-50-best-ask-bid-orders

        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :param str[] symbols: unified array of symbols
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.method]: either '/market/level2' or '/spotMarket/level2Depth5' or '/spotMarket/level2Depth50' default is '/market/level2'
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        r   zA watchOrderBookForSymbols() requires a non-empty array of symbolsN   r   2   r-   z? watchOrderBook 'limit' argument must be None, 5, 20, 50 or 100Fr!   r2   r/   /spotMarket/level2Depthr   r   
orderbook:)r2   r   r   )ry   r   ri   r   r   r   r   rL   r   rl   r   rx   r   handle_order_book_subscriptionr   r   )r<   r   r   rH   r   r   rp   r2   rk   r|   r}   r~   r   r   rs   	orderbooks                   r>   r   z#kucoin.watch_order_book_for_symbolsx  s     GA#DGG.q$qrr%3,Ub[uPQz#DGG.o$opp!!!%%g.OOG,	NN5))66v?OQY[klQJERK.U;Fsxx	22q#g,' 	?AQZF  !67 |H%%fslX&=>		?
 %%=="L
 11#}eM_agiuvv	  1 	" *( ws7   A*F,F-:F'F(CF7F8FFFc                 z  K   | j                  |d      }| j                  |d      }| j                          d{    | j                  |dd      }| j	                  |      }| j                  d       d{   }d}| j                  |ddd      \  }}|dk(  s|dk(  rd	t        |      z   }|d
z   dj                  |      z   }g }g }	t        dt        |            D ]/  }
||
   }|j                  d|z          |	j                  d|z          1 ||dd|	d}| j                  ||||||       d{   S 7 7 7 w)a  

        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/level1-bbo-market-data
        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/level2-market-data
        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/level2-5-best-ask-bid-orders
        https://www.kucoin.com/docs/websocket/spot-trading/public-channels/level2-50-best-ask-bid-orders

        unWatches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :param str[] symbols: unified array of symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.method]: either '/market/level2' or '/spotMarket/level2Depth5' or '/spotMarket/level2Depth50' default is '/market/level2'
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        r   NFr!   r2   r/   r-   r   r   r   r   r   zunsubscribe:orderbook:r   Tr   )r|   r   r   rk   r   )rV   omitr   r   r   rL   r   rl   r   rx   ry   r   r   )r<   r   rH   r   r   rp   r2   rk   r|   r}   r~   r   rs   s                r>   r   z&kucoin.un_watch_order_book_for_symbols  sd     !!&'267+!!!%%gtU;OOG,	NN5))66v?OQY[klQJERK.U;Fsxx	22q#g,' 	=AQZF  !9F!BC%%lV&;<	=
 +  2
 //]E=Z`bnooo- 	" *& ps4   8D;D5<D;7D78B8D;0D91D;7D;9D;c                 4   | j                  |d      }| j                  |d      }| j                  |d      }|j                  d      }| j                  |d      }| j                  |d      }| j                  |d|      }	| j                  |	d d      }
d	|
z   }|d
k(  r_|
| j                  vr| j                         | j                  |
<   n| j                  |
   }|j                          |
| j                  |
   d<   n`|
| j                  vr| j                         | j                  |
<   | j                  |
   }| j                  |d      }| j                  |dd      }|t        |j                        }t        |j                  j                               }d }t        dt        |            D ]A  }||   }|j                  |      dk\  s|j                  |      dk\  s2|j                  |   } n | j                  |d      }| j!                  ddd      }||k(  r | j#                  | j$                  |||
|i        |j                  j'                  |       y ||k\  ry | j)                  | j                  |
   |       |j+                  | j                  |
   |       y )NrN   r   rk   r   rc   r   r   r   r   level2noncesequenceEndr   r   r!   r0   r-   )rD   rW   r   safe_symbol
orderbooks
order_bookresetrV   safe_integer_2ry   cachelistrn   keysrx   findhandle_optionrE   load_order_bookr   handle_deltar   )r<   rY   ru   rN   r   rk   
topicPartstopicSymboltopicChannelr   r   rq   r   r  deltaEndcacheLengthrn   rs   r~   keyr   r0   s                         r>   handle_order_bookzkucoin.handle_order_book  sq   R w/""7I6  '2[[%
&&z15''
A6##D(K@!!(D#6"V+hdoo-*.//*;' OOF3	!06DOOF#H-doo-*.//*;'/I%%i9E**4LH}!)//2 $V%9%9%>%>%@ A#q#m"45 A'*C-2,9OST9T'-';';C'@	
 )),@ $ 2 23C_VW X-/JJt33V[&RWY[\&&t,("$//&148tv.<r?   c                 @   | j                  |d      }| j                  |d      }| j                  |d      }||dz
  k  ryt        dt        |            D ]=  }||   }| j                  |d      }| j                  |d      }	||dz
  k\  s5||	k  s;|c S  t        |      S )Nr   r  sequenceStartrc   r  )rD   rV   rx   ry   )
r<   r   r  
firstDeltar  firstDeltaStartr~   delta
deltaStartr  s
             r>   get_cache_indexzkucoin.get_cache_index#  s    __UA.
!!)W5++JH?Q&&q#e*% 	A!HE**5/BJ((>Ha'eh.>	 5zr?   c                 V   | j                  |dd      }| j                  |d|      |d<   ||d<   | j                  |      |d<   | j                  |d|      }| j                  |dg       }| j                  |dg       }|d   }|d   }| j	                  ||       | j	                  ||       y )	Ntimer   r  r  r   changesr   r   )r  rV   r   rD   handle_bid_asks)	r<   r   r  r   r$  r   r   
storedBids
storedAskss	            r>   r  zkucoin.handle_delta1  s    ''v{C	!..umYO	'!*	+ $Y 7	*//%E:w3w3v&
v&
Z.Z.r?   c                     t        dt        |            D ]'  }| j                  ||         }|j                  |       ) y )Nr   )rx   ry   parse_bid_ask
storeArray)r<   bookSidebidAsksr~   bidAsks        r>   r%  zkucoin.handle_bid_asks>  s>    q#g,' 	(A''
3F'	(r?   c                 0   | j                  |d      }| j                  |d      }|2| j                  |d      }| j                  i |      | j                  |<   y t        dt        |            D ]&  }||   }| j                  i |      | j                  |<   ( y )Nr   r   r   r   )rV   rD   rW   r	  r  rx   ry   )r<   rY   ru   rs   r   r   r   r~   s           r>   r   z%kucoin.handle_order_book_subscriptionC  s    !!,8//,	:?%%lH=F&*oob%&@DOOF#1c'l+ E *.//"e*D'Er?   c                    | j                  |d      }||j                  vry | j                  |j                  |      }| j                  |j                  |      }|j                  |= | j                  |d      }|
 ||||       | j                  |dd      }|ro| j	                  |dg       }| j	                  |dg       }	t        dt        |            D ]  }
||
   }|	|
   }| j                  |||       ! | j                  |       y y )Nri   r2   r   Fr|   r   r   )	rW   rn   rD   	safe_boolr   rx   ry   clean_unsubscriptionclean_cache)r<   rY   ru   ri   rr   rs   r2   isUnSubr|   r   r~   rq   subHashs                r>   handle_subscription_statusz!kucoin.handle_subscription_statusR  s    gt,f***++F,@,@"Ev';';=MN  $x867L1..}eD NN<"MM#~~l<NPRS1c-01 H+A.*1-))&';GH \* r?   c                     |S N r<   rY   ru   s      r>   handle_system_statuszkucoin.handle_system_statusl  s	     r?   c           	        K   | j                          d{    | j                  |dd      }| j                  |ddg      }| j                  d       d{   }|rdnd}ddi}d}	|| j	                  |      }
|
d	   }|	d
z   |z   }	| j                  ||	|| j                  ||             d{   }| j                  r|j                  ||      }| j                  ||||d      S 7 7 7 ;w)a  
        watches information on multiple orders made by the user

        https://www.kucoin.com/docs/websocket/spot-trading/private-channels/private-order-change
        https://www.kucoin.com/docs/websocket/spot-trading/private-channels/stop-order-event

        :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.trigger]: trigger orders are watched if True
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        NstoptriggerTz/spotMarket/advancedOrdersr3   rG   ordersr   r   )
r   safe_value_2r  rL   r   rg   rm   r   r   filter_by_symbol_since_limit)r<   r   r   r   rH   r=  rp   rk   rt   rq   r   r>  s               r>   watch_orderszkucoin.watch_ordersy  s     !!!##FFI>6FI#67NN4((07,=Vd
 [[(FH%F%+f4K~~c;t{{7TZ?[\\??OOFE2E00tTT! 	" ) ]s4   C,C&?C,C(AC,.C*/8C,(C,*C,c                 <    dddddddd}| j                  |||      S )Nopenclosedcanceled	triggered)rC  filledmatchupdaterE  cancel	TRIGGERED)rW   )r<   statusstatusess      r>   parse_ws_order_statuszkucoin.parse_ws_order_status  s5    " $
 &&99r?   c           	         | j                  |d      }| j                  |      }| j                  |dd      }| j                  |d      }| j                  ||      }| j                  |d      }| j	                  |d      }|duxr |d u}	|dk(  r|	rd	}| j                  i d
|d|d   d| j                  |d      d| j                  |d      d|d| j                  |      dd d| j                  |d      dd dd d| j                  |d      d| j                  |dd      d|d|d| j                  |d      dd dd | j                  |d      d |d d d|      S )Nrj   	orderTime	createdAtr   	stopPricetriggerSuccessTrF  rE  r   ri   orderIdclientOrderId	clientOidr   r   lastTradeTimestamp	orderTypetimeInForcepostOnlysideprice
orderPricetriggerPriceamountsizecostaverage
filledSize)rG  	remainingrL  feer   )	rW   rN  r  r   rD   
safe_orderr   safe_string_lowersafe_string_2)
r<   orderr   rawTyperL  r   r   r^  rS  triggerFails
             r>   parse_ws_orderzkucoin.parse_ws_order  s	   L ""5&1++G4''{KH	##E84!!(F3''{;0@A%T1Sd8Rk!{F  
E 
fX& 
 $""5)4 
 T--e[A	 

  
 Y/ 
 !$ 
 D**5+> 
 4 
  
 D**5&9 
 T''wE 
  
 L 
 d&&uf5 
  D! 
" t# 
$ &&ul;- 
. / 	r?   c                    d}| j                  |d      }| j                  |d      }|| j                  ||       | j                  |      }| j                  |d      }| j                  |d      }| j                  |d      }	|	d u}
| j                  =| j                  | j                  dd      }t        |      | _        t        |      | _        |
r| j                  n| j                  }| j                  |j                  |i       }| j                  ||      }||d	   d
k(  rd
|d	<   |j                  |       |j                  ||       |dz   |z   }|j                  ||       y )Nr>  rN   tradeIdr   ri   r^  ordersLimitr+   rL  rD  r   )rD   rW   handle_my_traderl  r>  rV   r7   r   triggerOrdershashmapr   r   )r<   rY   ru   rq   rN   rn  parsedr   rT  r^  isTriggerOrderr   cachedOrdersr>  ri  symbolSpecificMessageHashs                   r>   handle_orderzkucoin.handle_order  s\   * w/""43  1$$T*!!&(3""640v~>&d2;;%%dllM4HE07DK!7!>D-;t))!5!5vrB0X(*#+x F#|[1$/#$5$>!|%>?r?   c           	        K   | j                          d{    | j                  d       d{   }d}| j                  |ddd      \  }}ddi}d}|!| j                  |      }	|	d   }|d	z   |	d   z   }| j	                  |||| j                  ||             d{   }
| j                  r|
j                  ||      }| j                  |
|||d      S 7 7 7 ;w)
a  
        watches information on multiple trades made by the user

        https://www.kucoin.com/docs/websocket/spot-trading/private-channels/private-order-change

        :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
        :param str [params.method]: '/spotMarket/tradeOrders' or '/spot/tradeFills' default is '/spotMarket/tradeOrders'
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        NTr#   r2   r3   rG   myTradesr   r   )	r   rL   r   r   rg   rm   r   r   r@  )r<   r   r   r   rH   rp   rk   rt   rq   r   r   s              r>   watch_my_tradeszkucoin.watch_my_trades  s      !!!NN4((55foxYrsvd
 ![[(FH%F%+fX.>>K~~c;t{{7TZ?[\\??OOFE2E00tTT 	"( ]s2   CCCCA-CC8CCCc                    | j                   -| j                  | j                  dd      }t        |      | _         | j	                  |d      }| j                  |      }| j                   }|j                  |       d}|j                  | j                   |       |dz   |d   z   }|j                  | j                   |       y )Nr4   r+   rN   ry  r   r   )ry  rV   r7   r   r   parse_ws_trader   r   )	r<   rY   ru   r   rN   rs  ry  rq   rv  s	            r>   rp  zkucoin.handle_my_trade;  s    : == %%dllM4HE259DM~~gv.$$T*== t}}k2$/#$5x8H$H!t}}&?@r?   c                 z   | j                  |d      }| j                  ||d      }|d   }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }	|$| j                  |d      }| j                  |d	      }	| j                  |d
      }
| j                  |ddd      }|d   }| j                  |d      }| j                  |d      }| j                  ||| j	                  |      |||
|| j                  |d      |||	d |||dd|      S )Nr   r   rX  r[  rn  
matchPrice	matchSizer\  r`  rT  tsr#  gư>quotefeeRatere  	liquidity)ra  ratecurrency)r   r   r   r   ri   ri  rj   takerOrMakerr[  r\  r_  ra  re  )rW   r   safe_integer_product_2
safe_trader   )r<   r   r   r   r   rj   r[  rn  r\  r_  ri  r   feeCurrencyr  feeCosts                  r>   r|  zkucoin.parse_ws_traded  sp   R ##E84!!(FC8!{3v.""5)4  5!!%5=$$UG4E%%eV4F  	2//tVXN	Wo""5)4""5%0"Y/ ,,UK@' 
$ % 	r?   c           	         K   | j                          d{    | j                  d       d{   }d}ddi}d}| j                  |||| j                  ||             d{   S 7 Q7 :7 w)a  
        watch balance and get the amount of funds available for trading or funds locked in orders

        https://www.kucoin.com/docs/websocket/spot-trading/private-channels/account-balance-change

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        NTz/account/balancerG   balance)r   rL   rg   rm   )r<   rH   rp   rk   rt   rq   s         r>   watch_balancezkucoin.watch_balance  sw      !!!NN4(("d
  ^^CeT[[RX=YZZZ 	"( [s1   A.A(A.A*3A.#A,$A.*A.,A.c                    | j                  |di       }d}| j                  |d      }| j                  |d      }d }|#|j                  d      }| j                  |d      }| j                  | j                  ddd	      }	| j                  | j                  d
      }
| j                  |
|d	      }|| j
                  vri | j
                  |<   || j
                  |   d<   | j                  |d      }|| j
                  |   d<   | j                  |      | j
                  |   d<   | j                  |      }| j                         }| j                  |d      |d<   | j                  |d      |d<   | j                  |d      |d<   || j
                  |   |<   | j                  | j
                  |         | j
                  |<   ||	k(  r |j                  | j
                  |   |       y y )NrN   r  r  relationEvent.r   r)   defaultTyper   accountsByTyper   r#  r   r   	availablefreeholdusedtotal)rD   rW   r   rh  r7   r  rV   r   safe_currency_codeaccountsafe_balancer   )r<   rY   ru   rN   rq   
currencyIdr  requestAccountTyperelationEventPartsselectedTyper  uniformTyper   coder  s                  r>   handle_balancezkucoin.handle_balance  s   0 w3%%dJ7
((?!$!.!4!4S!9!%!1!12Da!H))$,,W^_7GH&&~7I7St||+(*DLL%,0[!&)%%dF3	1:[!+.04Y0G[!*-&&z2,,.**4=**48++D':*1[!$'$($5$5dll;6O$P[!,&NN4<<4kB 'r?   c                    | j                  |d      }|dk(  r| j                  ||       y | j                  |d      }| j                  | j                  | j                  | j                  | j                  | j                  | j
                  | j                  | j                  | j                  | j                  d}| j                  ||      }|
 |||       y y )Nrk   z/market/ticker:allr   )level1r  ztrade.l2updateztrade.tickerztrade.snapshotztrade.l3matchztrade.candles.updatezaccount.balanceorderChange	stopOrderz/spot/tradeFills)
rW   r   r   r  r   r   r  rw  rp  rD   )r<   rY   ru   rk   r   methodsr2   s          r>   handle_subjectzkucoin.handle_subject  s    "   '2((vw/""7I6)),,"44 .."00!..$($5$5#22,,** $ 4 4
 '267# r?   c                 >    t        | j                               }|ddS )Nr5   )ri   rj   )rl   re   )r<   rY   ri   s      r>   r5   zkucoin.ping  s%     "#
 	
r?   c                 .    | j                         |_        y r7  )millisecondslastPongr9  s      r>   handle_pongzkucoin.handle_pong(  s    ++-r?   c                     | j                  |dd      }|dk(  r4d}|j                  j                  d      dk\  rd}d | j                  d   |<   | j	                  d d |j                  d d ||d d 	       y )	NrN    ztoken is expiredrB   zconnectId=privater   rA   rC   )rW   rp   r  r7   handle_errors)r<   rY   ru   rN   rj   s        r>   handle_error_messagezkucoin.handle_error_message,  sw     4%%Dzz23q8 )-DLL &4vzz4tWdTXYr?   c                     | j                  |d      }| j                  | j                  | j                  | j                  | j
                  d}| j                  ||      }|
 |||       y y )Nrj   )welcomeackru   pongerror)rW   r:  r5  r  r  r  rD   )r<   rY   ru   rj   r  r2   s         r>   handle_messagezkucoin.handle_message=  sq    0 0022**$$..
 $/67# r?   r7  )A__name__
__module____qualname__r   r;   rL   rF   re   rg   r   dictr   rl   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   r5  r:  r   r	   rA  rN  rl  rw  rz  rp  r|  r   r  r  r  r5   r  r  r  __classcell__)r=   s   @r>   r   r      s   +# +Z 68  =? +Z
 JLZ^ [ ^`nr h  acy} hrv h$ 68 D DF D& 6:" 'E7 'E 'ERL.F L.\ 8<B FW F7 F" Y]eg U Ug U02V 2** 8<$]ajl H HC HWZ Hquvzq{ H2(,6 (,T <@d[] S SS S Sbfglbm S OSaenp  Sd3i  S  S[^  Suyz  vA  SD LN pc pRU p< 9; 
HC 
Hs 
H,6 ,@ @DB PS P PS\ P@ =? L L3 L  SW_a -!$s) -!C -!fo -!^ PR &pT#Y &pVY &pPR= R=h/(
	EV 	E+ +46  04$UYbd U UC Us Uimnsit U@
:GR-@6 -@^ 37TX\eg UC Us URU Ulpqvlw U<'Af 'ARL\ *, [ [$1CV 1Cf%$V %$N
6 
.& .Z6 Z"$V $r?   r   )ccxt.async_supportccxt ccxt.async_support.base.ws.cacher   r   r   ccxt.base.typesr   r   r   r	   r
   r   r   r   r   r   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   r   async_supportr   r8  r?   r>   <module>r     s?     f f f f f 4  * .z$T&& z$r?   