
    ":h                         d dl Zd dlmZmZmZ d dlmZmZm	Z	m
Z
mZmZmZmZmZmZmZ d dlmZ d dlmZ d dlmZ d dlmZ  G d d	ej2                  j4                        Zy)
    N)
ArrayCacheArrayCacheBySymbolByIdArrayCacheByTimestamp)AnyBalancesIntOrder	OrderBookPositionStrStringsTickerTickersTrade)Client)List)ExchangeError)ArgumentsRequiredc            
       4    e Zd Zdef fdZi fdZi fdZd Zi fdZi 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d>dZdi fdedefdZd ZdedefdZ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defdZ$i fde e   defd Z%defd!Z&d"ddi fdededede e'   fd#Z(defd$Z)di fdedede*fd%Z+di fde e   dede*fd&Z,i fdedefd'Z-i fde e   defd(Z.d) Z/d* Z0defd+Z1d, Z2defd-Z3dddi fdededede e4   fd.Z5d/ Z6d>d0Z7defd1Z8i fde9fd2Z:defd3Z;defd4Z<d5 Z=defd6Z>d>d7edefd8Z?defd9Z@defd:ZAdefd;ZBdefd<ZCdefd=ZD xZES )?kucoinfutures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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+| j                  id,      S )-NwsTwatchLiquidationsFwatchLiquidatinsForSymbolswatchMyLiquidationswatchMyLiquidationsForSymbolswatchTickerwatchTickerswatchBidsAskswatchTrades
watchOHLCVwatchOrderBookwatchOrderswatchBalancewatchPositionwatchPositionswatchPositionForSymbolswatchTradesForSymbolswatchOrderBookForSymbols1min5min15min30min1hour2hour4hour8hour12hour1day1week1month)1m3m5m15m30m1h2h4h8h12h1d1w1Mfuturemargin)swapcross        )snapshotDelaysnapshotMaxRetries)fetchPositionSnapshotawaitPositionSnapshot)
timeframesaccountsByTypetradesLimitr#   r&   ping)hasoptions	streaming)deep_extendsuperr   describerR   )self	__class__s    P/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/pro/kucoinfutures.pyrX   zkucoinfutures.describe   st   mT C Ed#U -e &t	
 0 t    t d !$ t    !%  *5!" (#$ +D%, !  ""!!!!# !"  %%#  $%'*+#
 .2-1"E&V 			yBH
 B B	    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_valuerT   spawnnegotiate_helper)rY   privateChannelparams	connectIdr`   spawanedrD   s          r[   	negotiatezkucoinfutures.negotiateV   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)Nr^   r_   datainstanceServersr   pingIntervalendpointtoken?)rn   rd   rf   r`   )futuresPrivatePostBulletPrivatefuturesPublicPostBulletPublicra   safe_integersafe_string	urlencodeclient	keepAlive	ExceptionrT   reject)rY   rd   re   responserf   rj   rk   firstInstanceServerrl   rm   rn   resultru   erD   s                  r[   rc   zkucoinfutures.negotiate_helperd   sN    !/IX	'	0!%!E!Ef!MM& "&!C!CF!KK??8VR8D"ood4ErJO"&///1"E,,-@.QL''(;ZHH$$T73E^dnn"0&6 ' F
 [[(F+FMC N& L  	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      )sumrr   rT   )rY   r~   s     r[   
request_idzkucoinfutures.request_id   s9    HHT..t||[!LaP	$-[!r\   c                    K   t        | j                               }|d|dd}| j                  ||      }d|i}	||	}n| j                  |	|      }| j                  |||||       d {   S 7 w)N	subscribeTidtypetopicry   r   )strr   extendwatch)
rY   urlmessageHashsubscriptionHashsubscriptionre   r~   requestmessagesubscriptionRequests
             r[   r   zkucoinfutures.subscribe   s     )*	%	
 ++gv.)%
 .L;;':LILZZ[';K\ZZZZs   A&A/(A-)A/c                    K   t        | j                               }|d|dd}| j                  ||| j                  ||      ||       d {   S 7 w)Nr   Tr   )r   r   watch_multipler   )	rY   r   messageHashesr   subscriptionHashessubscriptionArgsre   r~   r   s	            r[   subscribe_multiplez kucoinfutures.subscribe_multiple   se     )*		
 ((mT[[RX=Y[mo  A  A  	A  As   A	AAANr   c                 V  K   t        | j                               }|d|dd}| j                  ||      }	||||<   | j                  |      }
t	        dt        |            D ]%  }||   }||
j                  vs||
j                  |<   ' | j                  |||	||       d {   S 7 w)NunsubscribeTr   r   )r   r   r   ru   rangelensubscriptionsr   )rY   r   r   r   r   re   r   r~   r   r   ru   ir   s                r[   un_subscribe_multiplez#kucoinfutures.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   }d|d<   | j                  |g|       d{   }||   S 7 ?7 w)a  
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://www.kucoin.com/docs/websocket/futures-trading/public-channels/get-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   r   callerMethodName)load_marketsmarketwatch_tickers)rY   r   re   r   tickerss        r[   watch_tickerzkucoinfutures.watch_ticker   si      !!!V$!%2!"**F8V<<v 	" =s!   AA5AA
AAsymbolsc                    K   | j                          d{    | j                  dd||       d{   }| j                  ri }|||d   <   |S | j                  | j                  d|      S 7 U7 ;w)a  
        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
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        Nr   z/contractMarket/ticker:r   )r   watch_multi_request
newUpdatesfilter_by_arrayr   rY   r   re   tickerr   s        r[   r   zkucoinfutures.watch_tickers   sx      !!!//@Y[bdjkk??G(.GF8$%N##DLL(GDD 	"ks   A0A,A0A.:A0.A0ru   c                    | j                  |di       }| j                  |d      }| j                  |d d      }| j                  ||      }|| j                  |d   <   |j	                  || j                  d|d                y )Nrj   r   -r   )ra   safe_marketparse_tickerr   resolveget_message_hash)rY   ru   r   rj   marketIdr   r   s          r[   handle_tickerzkucoinfutures.handle_ticker   s    , w3??42!!(D#6""40)/VH%&vt44Xvh?OPQr\   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/futures-trading/public-channels/get-ticker-v2

        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/contractMarket/tickerV2:Nr   )r   r   r   bidsasksr   s        r[   watch_bids_askszkucoinfutures.watch_bids_asks  sc      //A\^egmnn??G(.GF8$%N##DMM8WEE os   AA:AchannelNamec                   K   | j                          d {    | j                  |d|      \  }}|dk(  }| j                  |d ddd      }t        |      }|dkD  rt	        | j
                  dz   |z   dz         g }t        dt        |            D ]B  }||   }	| j                  |	      }
|rd	nd
}|j                  | j                  ||
d                D | j                  d       d {   }| j                  |      }dj                  |      }t        | j                               }|d||z   dd}d|i}| j                  ||| j!                  ||      ||       d {   S 7 N7 }7 	w)Nr   r    FTd    z#() accepts a maximum of 100 symbolsr   bidaskr   r   ,r   r   r   )r   handle_param_stringmarket_symbolsr   r   r   r   r   appendr   rh   
market_idsjoinr   r   r   r   )rY   
methodNamer   r   re   
isBidsAskslengthr   r   r   r   prefixr   	marketIdsjoinedr~   r   r   s                     r[   r   z!kucoinfutures.watch_multi_request  s    !!!!55f>PR\]
F O3
%%gtUD%HWC<#DGGcMJ$>Af$fggq#g,' 	RAQZF[[(F!+XF  !6!6vvh?O!PQ		R
 NN5))OOG,	)$)*	 6)	
 )
 ((mT[[RX=Y[hjvwww5 	" * xs5   E+E$CE+)E'*A5E+E) E+'E+)E+c                     | j                  |      }|d   }|| j                  |<   |j                  || j                  d|             y )Nr   r   )parse_ws_bid_askr   r   r   )rY   ru   r   parsedTickerr   s        r[   handle_bid_askzkucoinfutures.handle_bid_ask/  sG    " ,,W5h' ,f|T%:%:8V%LMr\   c                    | j                  |di       }| j                  |d      }| j                  ||      }| j                  |d      }| j                  |dd      }| j	                  ||| j                  |      | j                  |d      | j                  |d      | j                  |d      | j                  |d      |d	|      S )
Nrj   r   tsư>bestAskPricebestAskSizebestBidPricebestBidSize)r   	timestampdatetimeask	askVolumebid	bidVolumeinfo)	safe_dictrs   r   safe_integer_productsafe_tickeriso8601safe_number)rY   r   r   rj   r   r   r   s          r[   r   zkucoinfutures.parse_ws_bid_askE  s    ~~ffb1##D(3!!(F3!!&(3--dD(C	"Y/##D.9))$>##D.9))$>	!
 	 		r\   c           
      P  K   |t        | j                  dz         | j                          d{    | j                  d       d{   }| j	                  |      }d|d   z   }ddi}d|d   z   }| j                  |      }| j                  ||       | j                  d	d
d      }	| j                  d	dd      }
| j                  |      }|	r"|
r ||j                  d|z          d{   }|S | j                  |||d| j                  ||             d{   S 7 7 7 77 
w)av  
        watch open positions for a specific symbol

        https://docs.kucoin.com/futures/#position-change-events

        :param str|None symbol: unified market symbol
        :param dict params: extra parameters specific to the exchange API endpoint
        :returns dict: a `position structure <https://docs.ccxt.com/en/latest/manual.html#position-structure>`
        Nz+ watchPosition() requires a symbol argumentTz/contract/position:r   rd   	position:r   r&   rM   rN   fetchPositionSnapshot:)r   r   r   rh   r   ru   set_position_cachehandle_optionget_current_positionrD   r   r   )rY   r   re   r   r   r   r   r   ru   rM   rN   currentPositionsnapshots                r[   watch_positionzkucoinfutures.watch_positionV  s;     >#DGG.[$[\\!!!NN4((V$%t4d
 "F8$44S!/ $ 2 2?D[]a b $ 2 2?D[]a b33F; %:?V#]]+Cf+LMMHO^^CeT4;;wX^C_```! 	"( N`sF   .D&DD&	D 
B D&*D"+.D&D$D& D&"D&$D&c                     | j                   y | j                   j                  }| j                  ||i       }t        |j	                               }| j                  |d      S Nr   )	positionshashmapra   listvalues)rY   r   cachesymbolCacher   s        r[   r   z"kucoinfutures.get_current_positiont  sT    >>!&&ooeVR8k((*+vq))r\   c                     | j                  ddd      }|rDd|z   }||j                  vr0|j                  |       | j                  | j                  |||       y y y )Nr&   rM   Fr   )r   futuresrD   rb   load_position_snapshot)rY   ru   r   rM   r   s        r[   r   z kucoinfutures.set_position_cache|  s`     $ 2 2?D[]b c 2V;K6>>1k*

466VT 2 !r\   c                   K   | j                  |       d {   }t               | _        | j                  }|j                  |       |j                  |   }|j                  |       |j                  |d|z          y 7 fw)Nr   )fetch_positionr   r   r   r   r   )rY   ru   r   r   positionr   rD   s          r[   r   z$kucoinfutures.load_position_snapshot  sj     ,,V44/1X,uxv!56 5s   B A>A'B c                    | j                  |dd      }|j                  d      }| j                  |d      }| j                  |d d      }| j                  }| j	                  |      }d|z   }	| j                  |di       }
| j                  |
      }t        |j                               }t        dt        |            D ]  }||   }||   ||=  | j                  ||      }|j                  |       |j                  ||	       y )Nr    :r   r   rj   r   )rs   splitsafe_symbolr   r   ra   parse_positionr   keysr   r   r   r   r   )rY   ru   r   r   partsr   r   r   r   r   rj   newPositionr   r   keyr   s                   r[   handle_positionzkucoinfutures.handle_position  s   z   '26C ##E1-!!(D"533F;!F*w3))$/K$$&'q#d)$ 	%Aq'C3'$	% ;;<Xx-r\   sincelimitc                 H   K   | j                  |g|||       d{   S 7 w)a  
        get the list of most recent trades for a particular symbol

        https://docs.kucoin.com/futures/#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)rY   r   r  r  re   s        r[   watch_tradeszkucoinfutures.watch_trades  s'      22F8UE6RRRRs   " "c                   K   t        |      }|dk(  rt        | j                  dz         | j                          d{    | j	                  |      }| j                  d       d{   }| j	                  |      }| j                  |      }ddj                  |      z   }g }	g }
t        dt        |            D ]4  }||   }||   }|
j                  d|z          |	j                  d|z          6 | j                  ||
||	d|       d{   }| j                  r6| j                  |d      }| j                  |d      }|j                  ||      }| j                  |||d	d
      S 7 *7 7 aw)a  
        get the list of most recent trades for a particular symbol
        :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/contractMarket/execution:r   trades:r   r   T)r   r   r   r   r   rh   r   r   r   r   r   r   ra   rs   getLimitfilter_by_since_limit)rY   r   r  r  re   symbolsLengthr   r   r   r   r   r   r   r   tradesfirsttradeSymbols                    r[   r  z&kucoinfutures.watch_trades_for_symbols  sv     GA#DGG.n$noo!!!%%g.NN5))%%g.OOG,	,sxx	/BBq#g,' 	OAQZF |H  V!34%%&BX&MN		O
 ..sM5J\^bdjkk??OOFA.E**5(;KOOK7E))&%TRR% 	") ls5   <E0E()E0(E+)B#E0E.AE0+E0.E0c                 D   K   | j                  |g|       d{   S 7 w)af  
        unWatches trades stream

        https://docs.kucoin.com/futures/#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)un_watch_trades_for_symbolsrY   r   re   s      r[   un_watch_tradeszkucoinfutures.un_watch_trades+  s#      55vhGGGG     c                   K   | j                          d{    | j                  |dd      }| j                  d       d{   }| j                  |      }| j                  |      }d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!  
        get the list of most recent trades for a particular symbol
        :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   subMessageHashesr   r   r   )	r   r   rh   r   r   r   r   r   r   )rY   r   re   r   r   r   r   r   r   r   r   s              r[   r  z)kucoinfutures.un_watch_trades_for_symbols7  s     !!!%%gtU;NN5))%%g.OOG,	,sxx	/BBq#g,' 	:AQZF  !6!?@%%i&&89	:
 + 2
 //]E=Z`bnooo' 	")" ps4   C4C.+C4C0B&C4)C2*C40C42C4c                 R   | j                  |di       }| j                  |      }|d   }| j                  | j                  |      }|7| j                  | j                  dd      }t        |      }|| j                  |<   |j                  |       d|z   }|j                  ||       |S )Nrj   r   rQ   rH   r
  )ra   parse_trader  rr   rT   r   r   r   )	rY   ru   r   rj   trader   r  r  r   s	            r[   handle_tradezkucoinfutures.handle_tradeS  s    * w3  &xf5>%%dllM4HE&F"(DKKe&(v{+r\   r7   c                   K   | j                          d{    | j                  |      }| j                  d       d{   }| j                  |      }| j	                  | j
                  d      }| j                  |||      }	d|z   dz   |	z   }
d|z   dz   |z   }| j                  |||
d|       d{   }| j                  r|j                  ||      }| j                  |||dd      S 7 7 7 ;w)	a  

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

        watches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :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
        NFrO   z/contractMarket/limitCandle:_ohlcv::r   T)r   r   rh   	market_idr   rT   rs   r   r   r  r  )rY   r   	timeframer  r  re   r   r   rO   timeframeIdr   r   ohlcvs                r[   watch_ohlcvzkucoinfutures.watch_ohlcvu  s      !!!V$NN5))>>&)^^DLL,?
&&z9iH.9C?+M&(3.:nnS+udFKK??NN651E))%q$GG 	") Ls4   C1C+)C1 C-A2C13C/48C1-C1/C1c           	         | j                  |d      }|j                  d      }| j                  |d      }| j                  |d      }| j                  | j                  d      }| j	                  ||      }| j                  |d      }	| j                  |	      }
d|
z   dz   |z   }| j                  |d      }| j                  |d	      | j                  |d      | j                  |d
      | j                  |d      | j                  |d      | j                  |d      g}| j                  | j                  |
i       | j                  |
<   || j                  |
   vr8| j                  | j                  dd      }t        |      | j                  |
   |<   | j                  |
   |   }|j                  |       |j                  ||       y )Nr   r  r   rj   rO   r   r  candlesr      rJ         
OHLCVLimitrH   )rs   r   r   rT   find_timeframer   	safe_listrr   r   ohlcvsr   r   r   )rY   ru   r   r   r   r!  rj   rO   r   r   r   r   r"  parsedr  storeds                   r[   handle_ohlcvzkucoinfutures.handle_ohlcv  s   *   '2C &&ua0~~gv.^^DLL,?
''Z@	##D(3!!(+&(3.:tY/eQ'UA&UA&UA&UA&UA&
 #nnT[[&"EFT[[00%%dllL$GE-B5-IDKK	*V$Y/fv{+r\   c                 F   K   | j                  |g||       d{   S 7 w)a  
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
   1. After receiving the websocket Level 2 data flow, cache the data.
   2. Initiate a REST request to get the snapshot data of Level 2 order book.
   3. Playback the cached Level 2 data flow.
   4. Apply the new Level 2 data flow to the local snapshot to ensure that the sequence of the new Level 2 update lines up with the sequence of the previous Level 2 data. Discard all the message prior to that sequence, and then playback the change to snapshot.
   5. Update the level2 full data based on sequence according to the size. If the price is 0, ignore the messages and update the sequence. If the size=0, update the sequence and remove the price of which the size is 0 out of level 2. For other cases, please update the price.
   6. If the sequence of the newly pushed message does not line up to the sequence of the last message, you could pull through REST Level 2 message request to get the updated messages. Please note that the difference between the start and end parameters cannot exceed 500.

        https://docs.kucoin.com/futures/#level-2-market-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
        :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)rY   r   r  re   s       r[   watch_order_bookzkucoinfutures.watch_order_book  s%     " 66xOOOOs   !!c                   K   t        |      }|dk(  rt        | j                  dz         |"|dk7  r|dk7  rt        | j                  dz         | j	                          d{    | j                  |      }| j                  |      }| j                  d       d{   }dd	j                  |      z   }d
|i}g }	g }
t        dt        |            D ]4  }||   }||   }|
j                  d|z          |	j                  d|z          6 | j                  ||
||	||       d{   }|j                         S 7 7 7 w)a  
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://docs.kucoin.com/futures/#level-2-market-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
        :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 symbolsNrI   r   z8 watchOrderBook 'limit' argument must be None, 20 or 100F/contractMarket/level2:r   r  
orderbook:)r   r   r   r   r   r   r   rh   r   r   r   r   r  )rY   r   r  re   r  r   r   r   r   r   r   r   r   r   	orderbooks                  r[   r1  z*kucoinfutures.watch_order_book_for_symbols  sZ     GA#DGG.q$qrr%3,#DGG.h$hii!!!%%g.OOG,	NN5)))CHHY,??U"
  q#g,' 	LAQZF |H  !67%%&?(&JK		L
 11#}eM_aqsyzz	  ! 	" * {s7   A D>"D8#:D>D:BD>#D<$D>:D><D>c                 D   K   | j                  |g|       d{   S 7 w)a  
        unWatches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://docs.kucoin.com/futures/#level-2-market-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
        :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!kucoinfutures.un_watch_order_book  s#      996(FKKKKr  c                   K   | j                          d{    | j                  |      }| j                  |      }| j                  d       d{   }d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  
        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
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        NFr4  r   r   zunsubscribe:orderbook:r5  Tr6  )r   r   r   r   r  )	r   r   r   rh   r   r   r   r   r   )rY   r   re   r   r   r   r   r   r   r   r   s              r[   r8  z-kucoinfutures.un_watch_order_book_for_symbols   s      !!!%%g.OOG,	NN5)))CHHY,??q#g,' 	=AQZF  !9F!BC%%lV&;<	=
 +  2
 //]E=Z`bnooo% 	" * ps4   C!C:C!CBC!CC!C!C!c                    | j                  |d      |d<   | j                  |d      }||d<   | j                  |      |d<   | j                  |di       }|j                  d      }| j	                  |d      }| j                  |d      }| j	                  |d	      }|d
k(  rdnd}	||g}
|	dk(  r|d   }|j                  |
       y |d   }|j                  |
       y )Nsequencenoncer   r   changer   r   r   r&  buybidsasks)rr   r   ra   r   r   rs   
storeArray)rY   r6  deltar   r>  splitChangepricesidequantityr   value
storedBids
storedAskss                r[   handle_deltazkucoinfutures.handle_delta  s    !..ujA	'%%e[9	!*	+ $Y 7	*"5ll3'  a0Q/##K3%-vf!6>"6*J!!%("6*J!!%(r\   c                 b    t        dt        |            D ]  }| j                  |||           y r   )r   r   rK  )rY   booksidedeltasr   s       r[   handle_deltaszkucoinfutures.handle_deltas.  s0    q#f+& 	3Ahq	2	3r\   c                    | j                  |d      }| j                  |d      }|j                  d      }| j                  |d      }| j                  |d d      }d|z   }|| j                  vrN| j                  |j                  |i       }	| j                  |	d      }
| j                  i |
      | j                  |<   | j                  |   }| j                  |d      }| j                  |d	      }|.t        |j                        }|j                  d      }| j                  |d      }| j                  |d
      }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)                  ||       y )Nrj   r   r   r   r   r5  r  r=  r<  r   r#   rK      )ra   rs   r   r   
orderbooksr   r   rr   
order_bookr   r   r   r   r   findr   rb   load_order_bookr   rK  r   )rY   ru   r   rj   r   
topicPartsr   r   r   r   r  storedOrderBookr=  deltaEndcacheLengthtopicPartsNewtopicSymboltopicChannelr   r   r   r  rK   s                          r[   handle_order_bookzkucoinfutures.handle_order_book2  s4     w/  '2[[%
##J2!!(D#6"V+$//)#~~f.B.BE2N%%&6@E&*oob%&@DOOF#//&1!!/7;$$T:6=o334K!KK,M**=!<K++M1=L !5!5!:!:!<=ML1c-01 #A&HH[)Q.SXXl5Kq5P#)#7#7#<L	
 %%lG<E ../?RSTMm+

4//feUWX!!((.h/404r\   c                    | j                  |d      }| j                  |d      }| j                  |d      }||dz
  k  ryt        dt        |            D ]%  }||   }| j                  |d      }||dz
  k  s#|c S  t        |      S )Nr   r=  r<  r   )ra   rr   r   r   )	rY   r6  r   
firstDeltar=  firstDeltaStartr   rC  
deltaStarts	            r[   get_cache_indexzkucoinfutures.get_cache_indexf  s    __UA.
!!)W5++J
C?Q&&q#e*% 	A!HE**5*=JzA~%		
 5zr\   c                     |S N rY   ru   r   s      r[   handle_system_statusz"kucoinfutures.handle_system_statuss  s	     r\   c           
        K   | j                          d{    | j                  d       d{   }d}ddi}d}|| j                  |      }	|	d   }|dz   |z   }| j                  |||d| j	                  ||             d{   }
| j
                  r|
j                  ||      }| j                  |
|||d      S 7 7 7 ;w)a<  
        watches information on multiple orders made by the user

        https://docs.kucoin.com/futures/#trade-orders-according-to-the-market

        :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>`
        NTz/contractMarket/tradeOrdersrd   ordersr   r   )r   rh   r   r   r   r   r  filter_by_symbol_since_limit)rY   r   r  r  re   r   r   r   r   r   rj  s              r[   watch_orderszkucoinfutures.watch_orders  s      !!!NN4((-d
 [[(FH%F%+f4K~~c;tT[[QXZ`Eabb??OOFE2E00tTT 	"( cs2   CB<CB>ACC 8C>C Cc                 8    dddddd}| j                  |||      S )Nopenclosedcanceled)rn  filledmatchupdaterp  )rs   )rY   statusstatusess      r[   parse_ws_order_statusz#kucoinfutures.parse_ws_order_status  s/    "
 &&99r\   c                 r   | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }	| j                  |	      }
| j                  |dd	      }| j                  |d
      }| j	                  ||      }|d
   }| j                  |d      }| j                  i d|d
|d|d|d|d| j                  |      dd d|dd dd d|d|dd d|dd dd d|d |
d d d|      S )NorderId	clientOid	orderTyperE  
filledSizesizer   	orderTimer   r   rF  r   r   clientOrderIdr   r   lastTradeTimestamptimeInForcepostOnly	stopPriceamountcostaveragerq  )	remainingrt  feer  )rs   safe_string_lowerrv  r   r   
safe_orderr   )rY   orderr   r   r~  rz  rE  rq  r  rawTypert  r   r   r   rF  s                  r[   parse_ws_orderzkucoinfutures.parse_ws_order  s   $ eY/((<**5+>	  0!!%6!!%0""5&1++G4--e[(K	##E84!!(F3!%%eV4  
E 
f 
 " 
 ]	 

  
 Y/ 
 !$ 
 I 
 4 
  
 D 
 U 
  
 f 
 D 
  t! 
" f# 
$ + 
, - 	r\   c                 v   d}| j                  |d      }| j                  |      }| j                  |d      }| j                  |d      }|| j                  -| j	                  | j
                  dd      }t        |      | _        | j                  }	| j                  |	j                  |i       }
| j                  |
|      }|&| j                  |d      }|||d<   |d   d	k(  rd	|d<   |	j                  |       |j                  | j                  |       |d
z   |z   }|j                  | j                  |       y y )Nrj  rj   r   r   ordersLimitrH   r  rt  ro  r   )
ra   r  rs   rj  rr   rT   r   r   r   r   )rY   ru   r   r   rj   r-  r   rx  r  cachedOrdersrj  r  r  symbolSpecificMessageHashs                 r[   handle_orderzkucoinfutures.handle_order  s4   w/$$T*!!&(3""640{{"))$,,tL4U;;;L__\%9%962FFOOFG4E  OOE;?	(*3F;'?h.'/F8$'NN4;;4(3c(9F(B%NN4;;(AB# r\   c           
         K   | j                          d{    | j                  d       d{   }d}ddi}d| j                  i}d}| j                  ||||| j	                  ||             d{   S 7 `7 I7 w)a_  
        watch balance and get the amount of funds available for trading or funds locked in orders

        https://docs.kucoin.com/futures/#account-balance-events

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        NTz/contractAccount/walletrd   methodbalance)r   rh   handle_balance_subscriptionr   r   )rY   re   r   r   r   r   r   s          r[   watch_balancezkucoinfutures.watch_balance  s      !!!NN4(()d
 d66
  ^^Ce\4;;W^`fKghhh 	"( is2   A=A7A=A9AA=2A;3A=9A=;A=c                    | j                  |di       }|| j                  d<   | j                  |d      }| j                  |      }| j	                         }| j                  |d      |d<   | j                  |d      |d<   || j                  |<   | j                  | j                        | _        |j                  | j                  d       y )	Nrj   r   currencyavailableBalancefreeholdBalanceusedr  )ra   r  rs   safe_currency_codeaccountsafe_balancer   )rY   ru   r   rj   
currencyIdcoder  s          r[   handle_balancezkucoinfutures.handle_balance  s    " w3#V%%dJ7
&&z2,,.**41CD**4?$T((6t||Y/r\   c                 >    | j                  | j                  ||       y re  )rb   fetch_balance_snapshot)rY   ru   r   r   s       r[   r  z)kucoinfutures.handle_balance_subscription'  s    

4..@r\   c                 2  K   | j                          d {    | j                          d}| j                  | j                  ddd      }d|i}| j	                  |       d {   }t        |j                               }t        dt        |            D ]=  }||   }	|	dk7  s|	dk7  s|	d	k7  s|	d
k7  s |	dk7  s&|	dk7  s,||	   | j                  |	<   ? | j                  |di       | j                  d<   |j                  | j                  |       y 7 7 w)Nr  r%   defaultTyperF   r   r   r  r  totalr   r   r   )r   check_required_credentialssafe_string_2rT   fetch_balancer   r   r   r   r  ra   r   )
rY   ru   r   r   selectedTypere   r   r   r   r  s
             r[   r  z$kucoinfutures.fetch_balance_snapshot*  s    !!!'')))$,,W]^L
 ++F33D HMMO$q#d)$ 	4A7Dv~$&.TW_Q\I\aeisasx|  AG  yG%-d^T"	4  $xDVt||[1_ 	" 4sG   DDAD#D$?D$D*D0D6D<DADDc                 \   | j                  |d      }| j                  | j                  | j                  | j                  | j
                  | j                  | j                  | j                  | j                  | j                  | j                  d}| j                  ||      }|
 |||       y y )Nsubject)level2r   zcandle.sticktickerV2zavailableBalance.changerr  orderChangeorderUpdatedzposition.changezposition.settlementzposition.adjustRiskLimit)
rs   r]  r   r/  r   r  r  r  r  ra   )rY   ru   r   r  methodsr  s         r[   handle_subjectzkucoinfutures.handle_subject\  s     ""7I6,,(( --++'+':':&&,, --#33#'#7#7(,(<(<
 '267# r\   elementNamec                      ||dz   |z   S |dz   S )N@zs@allrf  )rY   r  r   s      r[   r   zkucoinfutures.get_message_hash{  s#    $v--((r\   c                 >    t        | j                               }|ddS )NrR   )r   r   )r   r   )rY   ru   r   s      r[   rR   zkucoinfutures.ping  s%     "#
 	
r\   c                 0    | j                         |_        |S re  )millisecondslastPongrg  s      r[   handle_pongzkucoinfutures.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 )	Nrj   r   ztoken is expiredr_   zconnectId=privater   r^   r`   )rs   r   rT  rT   handle_errors)rY   ru   r   rj   r   s        r[   handle_error_messagez"kucoinfutures.handle_error_message  sw     4%%Dzz23q8 )-DLL &4vzz4tWdTXYr\   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 )Nr   r  r   Fr   r  r   )	rs   r   ra   	safe_boolr+  r   r   clean_unsubscriptionclean_cache)rY   ru   r   r   r   r   r  isUnSubr   r  r   r   subHashs                r[   handle_subscription_statusz(kucoinfutures.handle_subscription_status  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                     | j                  |d      }| j                  | j                  | j                  | j                  | j
                  d}| j                  ||      }|
 |||       y y )Nr   )welcomer   pongerrorack)rs   rh  r  r  r  r  ra   )rY   ru   r   r   r  r  s         r[   handle_messagezkucoinfutures.handle_message  sq    0 00**$$..22
 $/67# r\   re  )F__name__
__module____qualname__r   rX   rh   rc   r   r   r   dictr   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
   r2  r1  r9  r8  rK  rO  r]  rc  rh  r	   rl  rv  r  r  r   r  r  r  r  r  r   rR   r  r  r  r  __classcell__)rZ   s   @r[   r   r      s   C# CJ 68  =? +Z
 XZ [$ pr A acy} hrv h$ 68  F " 6:" E7 E ERF R: 8<B FW F7 F" Z^fh x xw x:NV N," 26b a3 aX a<*U U U7m.f m.^ <@d[] S SS S Sbfglbm S OSaenp Sd3i S S[^ Suyz  vA S@ 9; 
HC 
Hs 
H LN pc pRU p8 6  D 8<$]ajl H HC HWZ Hquvzq{ H4-,6 -,^ @DB PS P PS\ P& SW_a !!$s) !!C !!fo !!F =? 
L 
L3 
L PR pT#Y pVY p6)&325 25h6  04$UYbd U UC Us Uimnsit U8:5nC6 C2 *, i i*0V 08A& A02d$V $>)C ) )
6 
& 
Z6 Z"+ +4$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   r   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   r   async_supportr   rf  r\   r[   <module>r     sB     f f p p p p 4  * .y$D&&44 y$r\   