
    i                         d dl Zd dl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j        j                  ZdS )
    N)
ArrayCacheArrayCacheBySymbolById)
BalancesIntOrder	OrderBookPositionStrStringsTickerTickersTrade)Client)List)ExchangeError)ArgumentsRequiredc            
           e Zd Z fdZi fdZi fdZd Zi fdZi 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d4d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 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$d  Z%d! Z&defd"Z'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& Z,d4d'Z-defd(Z.i fde/fd)Z0defd*Z1defd+Z2d, Z3defd-Z4d4d.e	defd/Z5d0 Z6defd1Z7defd2Z8defd3Z9 xZ:S )5kucoinfuturesc                     |                      t          t          |                                           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 )NTF)wswatchTickerwatchTickerswatchBidsAskswatchTradeswatchOrderBookwatchOrderswatchBalancewatchPositionwatchPositionswatchPositionForSymbolswatchTradesForSymbolswatchOrderBookForSymbolsfuturemargin)swapcross        )snapshotDelaysnapshotMaxRetries)fetchPositionSnapshotawaitPositionSnapshot)accountsByTypetradesLimitr   r   ping)hasoptions	streaming)deep_extendsuperr   describer0   )self	__class__s    \/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/pro/kucoinfutures.pyr6   zkucoinfutures.describe   s    mT : : C C E E# $!%#"&# $!%"'+0)-,0 " %%# #  $%'*+# #
 .2-1" "' 8 		Q.H
 .H
 . . .	    c                    K   |rdnd}|                      | j        di           }|                      ||          }|| d {V S |                     | j        ||          ||<   || j        d<   ||         }| d {V S )Nprivatepublicurls)
safe_valuer2   spawnnegotiate_helper)r7   privateChannelparams	connectIdr>   spawanedr#   s          r9   	negotiatezkucoinfutures.negotiateB   s      !/=IIX	t|VR88??433!>>>>>>! **T%:NFSSY#Vi||||||r:   c                   K   d }|rdnd}	 |r|                      |           d {V }n|                     |           d {V }|                     |di           }|                     |dg           }|                     |d          }|                     |d          }|                     |d          }	|                     |d          }
|	d	z   |                     |
||d
          z   }|                     |          }||_        |S # t          $ rN}|                     | j	        d         |          }|
                    |           | j	        d         |= Y d }~nd }~ww xY wd S )Nr<   r=   datainstanceServersr   pingIntervalendpointtoken?)rL   rB   rD   r>   )futuresPrivatePostBulletPrivatefuturesPublicPostBulletPublicr?   safe_integersafe_string	urlencodeclient	keepAlive	Exceptionr2   reject)r7   rB   rC   responserD   rH   rI   firstInstanceServerrJ   rK   rL   resultrS   er#   s                  r9   rA   zkucoinfutures.negotiate_helperP   s     !/=IIX	'	0 L!%!E!Ef!M!MMMMMMM& "&!C!CF!K!KKKKKKK??8VR88D"ood4ErJJO"&///1"E"E,,-@.QQL''(;ZHHH$$T733E^dnn"0&6 6 ' ' F
 [[((F+FM 	0 	0 	0__T\&%99EEFMM!V$Y//////	0 ts   C;D 
E AEE c                 z    |                      |                     | j        dd          d          }|| j        d<   |S )N	requestIdr      )sumrP   r2   )r7   r\   s     r9   
request_idzkucoinfutures.request_id}   s;    HHT..t|[!LLaPP	$-[!r:   c                    K   t          |                                           }|d|dd}|                     ||          }d|i}	||	}n|                     |	|          }|                     |||||           d {V S )N	subscribeTidtypetopicrW   rc   )strr_   extendwatch)
r7   urlmessageHashsubscriptionHashsubscriptionrC   r\   requestmessagesubscriptionRequests
             r9   ra   zkucoinfutures.subscribe   s      ))**	%	
 
 ++gv..)
 .LL;;':LIILZZ[';K\ZZZZZZZZZr:   c                    K   t          |                                           }|d|dd}|                     |||                     ||          ||           d {V S )Nra   Trb   )rf   r_   watch_multiplerg   )	r7   ri   messageHashesre   subscriptionHashessubscriptionArgsrC   r\   rm   s	            r9   subscribe_multiplez kucoinfutures.subscribe_multiple   s      ))**		
 
 ((mT[[RX=Y=Y[mo  A  A  A  A  A  A  A  A  	Ar:   symbolreturnc                    K   |                                   d{V  |                     |          }|d         }d|d<   |                     |g|           d{V }||         S )a  
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :see: 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>`
        Nrv   r   callerMethodName)load_marketsmarketwatch_tickers)r7   rv   rC   r{   tickerss        r9   watch_tickerzkucoinfutures.watch_ticker   s       !!!!!!!!!V$$!%2!"**F8V<<<<<<<<vr:   Nsymbolsc                    K   |                                   d{V  |                     dd||           d{V }| j        ri }|||d         <   |S |                     | j        d|          S )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:rv   )rz   watch_multi_request
newUpdatesfilter_by_arrayr}   r7   r   rC   tickerr}   s        r9   r|   zkucoinfutures.watch_tickers   s       !!!!!!!!!//@Y[bdjkkkkkkkk? 	G(.GF8$%N##DL(GDDDr:   rS   c                 :   |                      |di           }|                      |d          }|                     |d d          }|                     ||          }|| j        |d         <   |                    ||                     d|d                              d S )NrH   rv   -r   )r?   safe_marketparse_tickerr}   resolveget_message_hash)r7   rS   rn   rH   marketIdr{   r   s          r9   handle_tickerzkucoinfutures.handle_ticker   s    , w33??422!!(D#66""400)/VH%&vt44Xvh?OPPQQQQQr:   c                    K   |                      dd||           d{V }| j        ri }|||d         <   |S |                     | j        d|          S )a  
        :see: 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:Nrv   )r   r   r   bidsasksr   s        r9   watch_bids_askszkucoinfutures.watch_bids_asks   ss       //A\^egmnnnnnnnn? 	G(.GF8$%N##DM8WEEEr:   channelNamec                 F  K   |                                   d {V  |                     |d|          \  }}|dk    }|                     |d ddd          }t          |          }|dk    rt	          | j        dz   |z   dz             g }t          dt          |                    D ]T}||         }	|                     |	          }
|rd	nd
}|                    | 	                    ||
d                              U| 
                    d           d {V }|                     |          }d                    |          }t          |                                           }|d||z   dd}d|i}|                     |||                     ||          ||           d {V S )Nry   r   FTd    z#() accepts a maximum of 100 symbolsr   bidaskr   rv   ,ra   rb   rc   )rz   handle_param_stringmarket_symbolslenr   rc   ranger{   appendr   rF   
market_idsjoinrf   r_   rq   rg   )r7   
methodNamer   r   rC   
isBidsAskslengthrr   irv   r{   prefixri   	marketIdsjoinedr\   rm   rl   s                     r9   r   z!kucoinfutures.watch_multi_request   s     !!!!!!!!!!55f>PR\]]
F O3
%%gtUD%HHWC<<#DGcMJ$>Af$fgggq#g,,'' 	R 	RAQZF[[((F!+9XXF  !6!6vvh?O!P!PQQQQNN5))))))))OOG,,	)$$))**	 6)	
 
 )
 ((mT[[RX=Y=Y[hjvwwwwwwwwwr:   c                     |                      |          }|d         }|| j        |<   |                    ||                     d|                     d S )Nrv   r   )parse_ws_bid_askr   r   r   )r7   rS   rn   parsedTickerrv   s        r9   handle_bid_askzkucoinfutures.handle_bid_ask  sW    " ,,W55h' ,f|T%:%:8V%L%LMMMMMr:   c                    |                      |di           }|                     |d          }|                     ||          }|                     |d          }|                     |dd          }|                     |||                     |          |                     |d          |                     |d          |                     |d          |                     |d          |d	|          S )
NrH   rv   tsư>bestAskPricebestAskSizebestBidPricebestBidSize)rv   	timestampdatetimeask	askVolumebid	bidVolumeinfo)	safe_dictrQ   r   safe_integer_productsafe_tickeriso8601safe_number)r7   r   r{   rH   r   rv   r   s          r9   r   zkucoinfutures.parse_ws_bid_ask  s    ~~ffb11##D(33!!(F33!!&(33--dD(CC	"Y//##D.99))$>>##D.99))$>>	!
 	!
 	 	 		r:   c           
        K   |t          | j        dz             |                                  d{V  |                     d           d{V }|                     |          }d|d         z   }ddi}d|d         z   }|                     |          }|                     ||           |                     d	d
d          }	|                     d	dd          }
| 	                    |          }|	r$|
r"| |
                    d|z              d{V }|S |                     |||d|                     ||                     d{V S )az  
        watch open positions for a specific symbol
        :see: 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:rc   rB   	position:rv   r   r,   r-   fetchPositionSnapshot:)r   rc   rz   rF   r{   rS   set_position_cachehandle_option	safe_boolget_current_positionr#   ra   rg   )r7   rv   rC   ri   r{   re   rm   rj   rS   r,   r-   currentPositionsnapshots                r9   watch_positionzkucoinfutures.watch_position,  s      >#DG.[$[\\\!!!!!!!!!NN4((((((((V$$%t4d
 "F8$44S!!/// $ 2 2?D[]a b b $@WY] ^ ^33F;;  	%: 	?V#]]+Cf+LMMMMMMMMHO^^CeT4;;wX^C_C_`````````r:   c                     | j         d S | j         j        }|                     ||i           }t          |                                          }|                     |d          S Nr   )	positionshashmapr?   listvalues)r7   rv   cachesymbolCacher   s        r9   r   z"kucoinfutures.get_current_positionH  s[    >!4&ooeVR88k((**++vq)))r:   c                     |                      ddd          }|rBd|z   }||j        vr6|                    |           |                     | j        |||           d S d S d S )Nr   r,   Fr   )r   futuresr#   r@   load_position_snapshot)r7   rS   rv   r,   rj   s        r9   r   z kucoinfutures.set_position_cacheP  s     $ 2 2?D[]b c c  	U2V;K6>11k***

46VTTTTT		U 	U11r:   c                   K   |                      |           d {V }t                      | _        | j        }|                    |           |j        |         }|                    |           |                    |d|z              d S )Nr   )fetch_positionr   r   r   r   r   )r7   rS   rj   rv   positionr   r#   s          r9   r   z$kucoinfutures.load_position_snapshotX  s      ,,V44444444/11X,uxv!566666r:   c                 |   |                      |dd          }|                    d          }|                      |d          }|                     |d d          }| j        }|                     |          }d|z   }	|                     |di           }
|                     |
          }t          |                                          }t          dt          |                    D ]}||         }||         ||= |                     ||          }|                    |           |                    ||	           d S )Nre    :r]   r   rH   r   )rQ   splitsafe_symbolr   r   r?   parse_positionr   keysr   r   rg   r   r   )r7   rS   rn   re   partsr   rv   r   r   rj   rH   newPositionr   r   keyr   s                   r9   handle_positionzkucoinfutures.handle_positionb  s9   z   '266C  ##E1--!!(D"5533F;;!F*w33))$//K$$&&''q#d))$$ 	% 	%Aq'C3'$;;<<Xx-----r:   sincelimitc                 D   K   |                      |g|||           d{V S )a  
        get the list of most recent trades for a particular symbol
        :see: 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)r7   rv   r   r   rC   s        r9   watch_tradeszkucoinfutures.watch_trades  s6       22F8UE6RRRRRRRRRr:   c                 B  K   t          |          }|dk    rt          | j        dz             |                                  d{V  |                     |          }|                     d           d{V }|                     |          }|                     |          }dd                    |          z   }g }	g }
t          dt          |                    D ]B}||         }||         }|
	                    d|z              |		                    d|z              C| 
                    ||
||	d|           d{V }| j        rB|                     |d          }|                     |d          }|                    ||          }|                     |||d	d
          S )a  
        get the list of most recent trades for a particular symbol
        :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>`
        r   z> watchTradesForSymbols() requires a non-empty array of symbolsNFz/contractMarket/execution:r   trades:rv   r   T)r   r   rc   rz   r   rF   r   r   r   r   ru   r   r?   rQ   getLimitfilter_by_since_limit)r7   r   r   r   rC   symbolsLengthri   r   re   rs   rr   r   rv   r   tradesfirsttradeSymbols                    r9   r   z&kucoinfutures.watch_trades_for_symbols  s      GA#DG.n$nooo!!!!!!!!!%%g..NN5))))))))%%g..OOG,,	,sxx	/B/BBq#g,,'' 	O 	OAQZF |H  V!3444%%&BX&MNNNN..sM5J\^bdjkkkkkkkk? 	8OOFA..E**5(;;KOOK77E))&%TRRRr:   c                 r   |                      |di           }|                     |          }|d         }|                      | j        |          }|5|                     | j        dd          }t          |          }|| j        |<   |                    |           d|z   }|                    ||           |S )NrH   rv   r/   r'   r   )r?   parse_trader   rP   r2   r   r   r   )	r7   rS   rn   rH   traderv   r   r   rj   s	            r9   handle_tradezkucoinfutures.handle_trade  s    * w33  &&xf55>%%dlM4HHE&&F"(DKe&(v{+++r:   c                 B   K   |                      |g||           d{V S )a^  
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
         *   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.
        :see: 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)r7   rv   r   rC   s       r9   watch_order_bookzkucoinfutures.watch_order_book  s4       66xOOOOOOOOOr:   c                   K   t          |          }|dk    rt          | j        dz             |#|dk    r|dk    rt          | j        dz             |                                  d{V  |                     |          }|                     |          }|                     d           d{V }dd	                    |          z   }d
|i}g }	g }
t          dt          |                    D ]B}||         }||         }|

                    d|z              |	
                    d|z              C|                     ||
||	||           d{V }|                                S )a  
        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
        :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 symbolsNr(   r   z8 watchOrderBook 'limit' argument must be None, 20 or 100Fz/contractMarket/level2:r   r   
orderbook:)r   r   rc   r   rz   r   r   rF   r   r   r   ru   r   )r7   r   r   rC   r   r   ri   re   rt   rs   rr   r   rv   r   	orderbooks                  r9   r   z*kucoinfutures.watch_order_book_for_symbols0  s      GA#DG.q$qrrr%3,,#DG.h$hiii!!!!!!!!!%%g..OOG,,	NN5)))))))))CHHY,?,??U
  q#g,,'' 	L 	LAQZF |H  !6777%%&?(&JKKKK11#}eM_aqsyzzzzzzzz	   r:   c                    |                      |d          |d<   |                      |d          }||d<   |                     |          |d<   |                     |di           }|                    d          }|                     |d          }|                     |d          }|                     |d	          }|d
k    rdnd}	||g}
|	dk    r|d         }|                    |
           d S |d         }|                    |
           d S )Nsequencenoncer   r   changer   r   r]      buybidsasks)rP   r   r?   r   r   rQ   
storeArray)r7   r   deltar   r   splitChangepricesidequantityrd   value
storedBids
storedAskss                r9   handle_deltazkucoinfutures.handle_deltaP  s"   !..ujAA	'%%e[99	!*	+ $Y 7 7	*"55ll3''  a00Q//##K33%--vvf!6>>"6*J!!%((((("6*J!!%(((((r:   c                 ~    t          dt          |                    D ]}|                     |||                    d S r   )r   r   r  )r7   booksidedeltasr   s       r9   handle_deltaszkucoinfutures.handle_deltasc  sH    q#f++&& 	3 	3Ahq	2222	3 	3r:   c                 &   |                      |d          }|                     |d          }|                    d          }|                     |d          }|                     |d d          }d|z   }|| j        vrP|                     |j        |i           }	|                     |	d          }
|                     i |
          | j        |<   | j        |         }|                     |d          }|                     |d	          }|Tt          |j
                  }|                    d          }|                     |d          }|                     |d
          }t          |j                                                  }d }t          d
t          |                    D ]K}||         }|                    |          d
k    r(|                    |          d
k    r|j        |         } nL|                     |d          }
|                     ddd          }||k    r|                     | j        ||||
i            |j
                            |           d S ||k    rd S |                     ||           |                    ||           d S )NrH   re   r   r]   r   r   r   r   r   r   r   r*      )r?   rQ   r   r   
orderbooksr   subscriptionsrP   
order_bookr   r   r   r   r   findr   r@   load_order_bookr   r  r   )r7   rS   rn   rH   re   
topicPartsr   rv   rj   rt   r   storedOrderBookr   deltaEndcacheLengthtopicPartsNewtopicSymboltopicChannelr  rl   r   r   r*   s                          r9   handle_order_bookzkucoinfutures.handle_order_bookg  s     w//  '22[[%%
##J22!!(D#66"V+$/))#~~f.BE2NN%%&6@@E&*oob%&@&@DOF#/&1!!/7;;$$T:66=o344K!KK,,M**=!<<K++M1==L !5!:!:!<!<==ML1c-0011  #A&HH[))Q..SXXl5K5Kq5P5P#)#7#<LE%%lG<<E ../?RSTTMm++

4/feUWXXX!((...FhF/400044444r:   c                 P   |                      |d          }|                     |d          }|                     |d          }||dz
  k     rdS t          dt          |                    D ]-}||         }|                     |d          }||dz
  k     r|c S .t          |          S )Nr   r   r   r]   )r?   rP   r   r   )	r7   r   r   
firstDeltar   firstDeltaStartr   r   
deltaStarts	            r9   get_cache_indexzkucoinfutures.get_cache_index  s    __UA..
!!)W55++J
CC?Q&&&2q#e**%% 	 	A!HE**5*==JzA~%% &5zzr:   c                     |S N r7   rS   rn   s      r9   handle_system_statusz"kucoinfutures.handle_system_status  s	     r:   c           
        K   |                                   d{V  |                     d           d{V }d}ddi}d}|%|                     |          }	|	d         }|dz   |z   }|                     |||d|                     ||                     d{V }
| j        r|
                    ||          }|                     |
|||d          S )a@  
        watches information on multiple orders made by the user
        :see: 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/tradeOrdersrB   ordersrv   r   )rz   rF   r{   ra   rg   r   r   filter_by_symbol_since_limit)r7   rv   r   r   rC   ri   re   rm   rj   r{   r'  s              r9   watch_orderszkucoinfutures.watch_orders  s      !!!!!!!!!NN4((((((((-d
 [[((FH%F%+f4K~~c;tT[[QXZ`EaEabbbbbbbb? 	3OOFE22E00tTTTr:   c                 @    dddddd}|                      |||          S )Nopenclosedcanceled)r+  filledmatchupdater-  )rQ   )r7   statusstatusess      r9   parse_ws_order_statusz#kucoinfutures.parse_ws_order_status  s7    "
 
 &&999r:   c                    |                      |d          }|                      |d          }|                     |d          }|                      |d          }|                      |d          }|                      |d          }|                      |d          }	|                     |	          }
|                     |dd	          }|                      |d
          }|                     ||          }|d
         }|                     |d          }|                     i d|d
|d|d|d|d|                     |          dd d|dd dd d|d|dd d|dd dd d|d |
d d d|          S )NorderId	clientOid	orderTyper  
filledSizesizerd   	orderTimer   rv   r  r   rc   clientOrderIdr   r   lastTradeTimestamptimeInForcepostOnly	stopPriceamountcostaverager.  )	remainingr1  feer   )rQ   safe_string_lowerr3  r   r   
safe_orderr   )r7   orderr{   rc   r;  r7  r  r.  r@  rawTyper1  r   r   rv   r  s                  r9   parse_ws_orderzkucoinfutures.parse_ws_order  s   $ eY//((<<**5+>>	  00!!%66!!%00""5&11++G44--e[(KK	##E844!!(F33!%%eV44  
E 
f 
 " 
 ]	 

  
 Y// 
 !$ 
 I 
 4 
  
 D 
 U 
  
 f 
 D 
  t! 
" f# 
$ + 
  
  
, -  	r:   c                    d}|                      |d          }|                     |          }|                     |d          }|                     |d          }|| j        0|                     | j        dd          }t          |          | _        | j        }	|                      |	j        |i           }
|                      |
|          }|.|                      |d          }|||d<   |d         d	k    rd	|d<   |	                    |           |	                    | j        |           |d
z   |z   }|	                    | j        |           d S d S )Nr'  rH   rv   rc   ordersLimitr'   r?  r1  r,  r   )
r?   rI  rQ   r'  rP   r2   r   r   r   r   )r7   rS   rn   rj   rH   parsedrv   r5  r   cachedOrdersr'  rG  r?  symbolSpecificMessageHashs                 r9   handle_orderzkucoinfutures.handle_order  s`   w//$$T**!!&(33""6400{"))$,tLL4U;;;L__\%962FFFOOFG44E  OOE;??	(*3F;'?h..'/F8$'''NN4;444(3c(9F(B%NN4;(ABBBBB# r:   c           
         K   |                                   d{V  |                     d           d{V }d}ddi}d| j        i}d}|                     |||||                     ||                     d{V S )ac  
        watch balance and get the amount of funds available for trading or funds locked in orders
        :see: 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/walletrB   methodbalance)rz   rF   handle_balance_subscriptionra   rg   )r7   rC   ri   re   rm   rl   rj   s          r9   watch_balancezkucoinfutures.watch_balance)  s       !!!!!!!!!NN4(((((((()d
 d6
  ^^Ce\4;;W^`fKgKghhhhhhhhhr:   c                    |                      |di           }|| j        d<   |                     |d          }|                     |          }|                                 }|                     |d          |d<   |                     |d          |d<   || j        |<   |                     | j                  | _        |                    | j        d           d S )	NrH   r   currencyavailableBalancefreeholdBalanceusedrR  )r?   rR  rQ   safe_currency_codeaccountsafe_balancer   )r7   rS   rn   rH   
currencyIdcoder\  s          r9   handle_balancezkucoinfutures.handle_balance<  s    " w33#V%%dJ77
&&z22,,..**41CDD**4??$T((66t|Y/////r:   c                 >    |                      | j        ||           d S r"  )r@   fetch_balance_snapshot)r7   rS   rn   rl   s       r9   rS  z)kucoinfutures.handle_balance_subscriptionX  s!    

4.@@@@@r:   c                 P  K   |                                   d {V  |                                  d}|                     | j        ddd          }d|i}|                     |           d {V }t          |                                          }t          dt          |                    D ]>}||         }	|	dk    r.|	dk    r(|	d	k    r"|	d
k    r|	dk    r|	dk    r||	         | j	        |	<   ?| 
                    |di           | j	        d<   |                    | j	        |           d S )NrR  r   defaultTyper%   rd   r   rX  rZ  totalr   r   r   )rz   check_required_credentialssafe_string_2r2   fetch_balancer   r   r   r   rR  r?   r   )
r7   rS   rn   rj   selectedTyperC   r   r   r   r_  s
             r9   rb  z$kucoinfutures.fetch_balance_snapshot[  sa     !!!!!!!!!'')))))$,W]^^L
 ++F33333333D HMMOO$$q#d))$$ 	4 	4A7Dv~~$&..TW__Q\I\I\aeisasasx|  AG  yG  yG%-d^T"#xDDVt|[11111r:   c                     |                      |d          }| j        | j        | j        | j        | j        | j        | j        | j        | j        | j        d
}|                     ||          }| |||           d S d S )Nsubject)
level2r   tickerV2zavailableBalance.changer/  orderChangeorderUpdatedzposition.changezposition.settlementzposition.adjustRiskLimit)	rQ   r  r   r   r`  r   rO  r   r?   )r7   rS   rn   rk  methodsrQ  s         r9   handle_subjectzkucoinfutures.handle_subject  s     ""7I66,(+'+':&, -#3#'#7(,(<
 
 '22F67##### r:   elementNamec                      ||dz   |z   S |dz   S )N@zs@allr#  )r7   rr  rv   s      r9   r   zkucoinfutures.get_message_hash  s#    $v--((r:   c                 N    t          |                                           }|ddS )Nr0   )rc   rd   )rf   r_   )r7   rS   rc   s      r9   r0   zkucoinfutures.ping  s0     ""##
 
 	
r:   c                 8    |                                  |_        |S r"  )millisecondslastPongr$  s      r9   handle_pongzkucoinfutures.handle_pong  s    ++--r:   c                     |                      |dd          }|dk    r2d}|j                            d          dk    rd}d | j        d         |<   |                     d d |j        d d ||d d 	  	         d S )	NrH   r   ztoken is expiredr=   zconnectId=privater   r<   r>   )rQ   ri   r  r2   handle_errors)r7   rS   rn   rH   rd   s        r9   handle_error_messagez"kucoinfutures.handle_error_message  s     44%%%Dz233q88 )-DL &4vz4tWdTXYYYYYr:   c                     |                      |d          }| j        | j        | j        | j        d}|                     ||          }| |||           d S d S )Nrd   )welcomern   pongerror)rQ   r%  rq  ry  r|  r?   )r7   rS   rn   rd   rp  rQ  s         r9   handle_messagezkucoinfutures.handle_message  sx    00 0*$.
 
 $//F67##### r:   r"  );__name__
__module____qualname__r6   rF   rA   r_   ra   ru   rf   r   r~   r   r   r|   r   r   r   r   r   r   r
   r	   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r   r%  r   r)  r3  rI  rO  r   rT  r`  rS  rb  rq  r   r0   ry  r|  r  __classcell__)r8   s   @r9   r   r      s       / / / / /b 68     =? + + + +Z  
 XZ [ [ [ [$ pr A A A A 68   F     6:" E E7 E E E E ERF R R R R: 8<B F FW F7 F F F F Z^fh x x xw x x x x:NV N N N N,   " 26b a a3 aX a a a a8* * *U U U U U U7 7 7m.f m. m. m. m.^ <@d[] 
S 
S 
SS 
S 
Sbfglbm 
S 
S 
S 
S OSaenp S Sd3i S S[^ Suyz  vA S S S S@ 6        D @DB P PS P PS\ P P P P" SW_a ! !$s) !C !fo ! ! ! !@) ) )&3 3 325 25 25 25 25h  6     04$UYbd U U UC Us Uimnsit U U U U4: : :5 5 5 5nC6 C C C C2 *, i i i i i i&0V 0 0 0 08A& A A A A02 02 02d$V $ $ $ $<) )C ) ) ) ) )
 
 
&    
Z6 Z Z Z Z"$V $ $ $ $ $ $ $ $r:   r   )ccxt.async_supportccxt ccxt.async_support.base.ws.cacher   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   r#  r:   r9   <module>r     s        O O O O O O O O k k k k k k k k k k k k k k k k k k k k k k k k 4 4 4 4 4 4       * * * * * * . . . . . .N$ N$ N$ N$ N$D&4 N$ N$ N$ N$ N$r:   