
    eik                        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mZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ  G d	 d
ej        j                  ZdS )    N)
ArrayCacheArrayCacheBySymbolByIdArrayCacheByTimestamp)AnyBalancesBoolIntOrder	OrderBookPositionStrStringsTickerTickersTrade)Client)List)ExchangeError)ArgumentsRequired)Precisec                   $    e Zd Zdef fdZdi fdZi fdZd Zi dfdZi dfd	e	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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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dJdZdddi fdededededee         f
dZdi f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.Z0defd/Z1defd0Z2dddi fde3dededee4         fd1Z5d2 Z6d3 Z7dJd4Z8defd5Z9dddi fde3dededee!         fd6Z:d7 Z;defd8Z<dJd9Z=i fde>fd:Z?defd;Z@d< ZAdefd=ZBdi fde3deCfd>ZDd? ZEdedefd@ZFdA ZGdefdBZHdefdCZIdefdDZJdefdEZKdedeLfdFZMdefdGZNdJdHede3fdIZO xZPS )Kkucoinreturnc                 :   |                      t          t          |                                           i ddddddddddddd	dd
ddddddddddddddddddddddddddddd	dddidddddddiddddddd d!| j        id"          S )#NwsTcreateOrderWsFeditOrderWsfetchOpenOrdersWsfetchOrderWscancelOrderWscancelOrdersWscancelAllOrdersWswatchBidsAskswatchOrderBookwatchOrderswatchPositionwatchPositionswatchMyTradeswatchTickerswatchTickerwatchTrades)	watchTradesForSymbolswatchOrderBookForSymbolswatchBalance
watchOHLCVunWatchTickerunWatchOHLCVunWatchOrderBookunWatchTradesunWatchhTradesForSymbols  
spotMethod/market/snapshot      /market/level2/contractMarket/level2)snapshotDelaysnapshotMaxRetriesr6   contractMethod/spotMarket/tradeOrders)fetchBalanceSnapshotawaitBalanceSnapshot)fetchPositionSnapshotawaitPositionSnapshot)tradesLimitr*   r$   r(   r.   r&   ping)hasoptions	streaming)deep_extendsuperr   describerE   )self	__class__s    M/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/pro/kucoin.pyrK   zkucoin.describe   s   fd 3 3 < < > >d u $U	
    !% $U   !$ t   !%     t!" t#$ *.,0 $"!% $$(!%,05  :  $ "4  &'*+"2&>	# # !";" -1,0! !
 .2-1" "% 6 		i:A
 :A
 : : :	    Fc                   K   |rdnd}|r|dz  }|                      | j        di           }|                     ||          }|| d {V S |                     | j        |||          ||<   || j        d<   ||         }| d {V S )NprivatepublicFuturesurls)	safe_dictrG   
safe_valuespawnnegotiate_helper)rL   privateChannelisFuturesMethodparams	connectIdrT   futures          rN   	negotiatezkucoin.negotiateO   s      !/=IIX	 	#"I~~dlFB77y11<<<<<< **T%:NIW]^^Y#Vi||||||rO   c                 N  K   d }	 |dk    r|                      |           d {V }n_|dk    r|                     |           d {V }n=|dk    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 )NrQ   rR   privateFuturesdatainstanceServersr   pingIntervalendpointtoken?)re   rY   r\   rT   )privatePostBulletPrivatepublicPostBulletPublicfuturesPrivatePostBulletPrivatefuturesPublicPostBulletPublicrU   	safe_listsafe_integersafe_string	urlencodeclient	keepAlive	ExceptionrV   rG   reject)rL   rY   r\   r[   responsera   rb   firstInstanceServerrc   rd   re   resultro   er]   s                  rN   rX   zkucoin.negotiate_helper_   s     +	0I%%!%!>!>v!F!FFFFFFF$ h&&!%!<!<V!D!DDDDDDD...!%!E!Ef!M!MMMMMMM!%!C!CF!K!KKKKKKK>>(FB77D"nnT3DbIIO"&..!"D"D,,-@.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   EE
 

F"AFF"c                     |                                   |                     |                     | j        dd          d          }|| j        d<   |                                  |S )N	requestIdr      )lock_idsumrl   rG   	unlock_id)rL   rx   s     rN   
request_idzkucoin.request_id   sX    HHT..t|[!LLaPP	$-[!rO   Nc                   K   t          |                                           }|d|dd}|                     ||          }|                     |          }	||	j        vr
||	j        |<   |                     |||||           d {V S )N	subscribeTidtypetopicrs   )strr}   extendro   subscriptionswatch)
rL   urlmessageHashsubscriptionHashr[   subscriptionrx   requestmessagero   s
             rN   r   zkucoin.subscribe   s      ))**	%	
 
 ++gv..S!! F$888.>F +ZZ[';K\ZZZZZZZZZrO   r   c                 J   K   |                      ||g||g||           d {V S N)un_subscribe_multiple)rL   r   r   r   r   r[   r   s          rN   un_subscribezkucoin.un_subscribe   s>      //k]EL\K]_egstttttttttrO   c                 `  K   t          |                                           }|d|dd}|                     ||          }	|                     |          }
t	          dt          |                    D ]}||         }||
j        vr
||
j        |<   |                     |||	||           d {V S )Nr   Tr   r   r   r}   r   ro   rangelenr   watch_multiplerL   r   messageHashesr   subscriptionHashesr[   r   rx   r   r   ro   ir   s                rN   subscribe_multiplezkucoin.subscribe_multiple   s      ))**		
 
 ++gv..S!!q#01122 	C 	CA1!4$(<<<2B$Y/((mWFXZfgggggggggrO   c                 n  K   t          |                                           }|d|dd}|                     ||          }	||||<   |                     |          }
t	          dt          |                    D ]}||         }||
j        vr
||
j        |<   |                     |||	||           d {V S )NunsubscribeTr   r   r   r   s                rN   r   zkucoin.un_subscribe_multiple   s      ))**	!	
 
 ++gv..#&/L#S!!q#01122 	C 	CA1!4$(<<<2B$Y/((mWFXZfgggggggggrO   symbolc                 b  K   |                                   d{V  |                     |          }|d         }|d         }|                     d|           d{V }d}|rd}n|                     |dd|          \  }}|d	z   |d
         z   }d|z   }|                     ||||           d{V S )a  
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://www.kucoin.com/docs-new/3470063w0
        https://www.kucoin.com/docs-new/3470081w0

        :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   contractFr7   /contractMarket/tickerr*   r6   :r   ticker:)load_marketsmarketr^   handle_option_and_paramsr   )	rL   r   r[   r   rZ   r   methodr   r   s	            rN   watch_tickerzkucoin.watch_ticker   s       !!!!!!!!!V$$! ,NN5/::::::::# 	h-FF!::6=R^`fggNFFvd|+&(^^CeVDDDDDDDDDrO   c                   K   |                                   d{V  |                     |          }|d         }|d         }|                     d|           d{V }d}|rd}n|                     |dd|          \  }}|d	z   |d
         z   }d|z   }d|z   }	||g|	|gdd|gd}
|                     ||||	||
           d{V S )a  
        unWatches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://www.kucoin.com/docs-new/3470063w0
        https://www.kucoin.com/docs-new/3470081w0

        :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   Fr7   r   r*   r6   r   r   zunsubscribe:ticker:r   tickerTr   subMessageHashesr   r   symbols)r   r   r^   r   r   )rL   r   r[   r   rZ   r   r   r   r   subMessageHashr   s              rN   un_watch_tickerzkucoin.un_watch_ticker   s-      !!!!!!!!!V$$! ,NN5/::::::::# 	h-FF!::6=R^`fggNFFvd|++f4"V+
 *51!/ 7x	
 	
 &&sKPVXdeeeeeeeeerO   r   c                   K   |                                   d{V  |                     |ddd          }|                     |          }d}|                     d||          \  }}|dk    o|dk    }|r|t	          | j        dz   |z   dz             d}d	}|rd
}n|                     |ddd|          \  }}g }g }	|vt          dt          |                    D ]X}
||
         }|	                    d|z              | 
                    |          }|		                    |dz   |d         z              Y|                     d|           d{V }d}|-|dz   }|                     ||||           d{V }| j        r|S ne|                     |          }|dz   d                    |          z   }|                     ||||	|           d{V }| j        ri }|||d         <   |S |                     | j        d|          S )a  

        https://www.kucoin.com/docs-new/3470063w0
        https://www.kucoin.com/docs-new/3470064w0
        https://www.kucoin.com/docs-new/3470081w0

        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]: *spot markets only* either '/market/snapshot' or '/market/ticker' default is '/market/ticker'
        :returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
        NTr)   spotmarginz/ watchTickers() requires a list of symbols for z marketstickersz/market/tickerr   r   r6   r   r   r   r   Fz:all,r   )r   market_symbolsget_market_from_symbolshandle_market_type_and_paramsr   r   handle_option_and_params_2r   r   appendr   r^   r   
newUpdates
market_idsjoinr   filter_by_arrayr   )rL   r   r[   firstMarket
marketTyperZ   r   r   r   topicsr   r   r   r   r   allTopic	marketIdssymbolsTopicnewDicts                      rN   watch_tickerszkucoin.watch_tickers  s      !!!!!!!!!%%gtT4@@227;;
!??P[]cdd
F%/MjH6L 	{w#DG._$_bl$loy$yzzz! 	u-FF!<<V^U]_kmsttNFF1c'll++ ; ; $$Y%7888V,,fslVD\9::::NN5/::::::::?H NN3XvNNNNNNNNG  00I!C<#((9*=*==L 33CV\^deeeeeeeeG  "-4)*##DL(GDDDrO   ro   c                 ~   |                      |d          }|                    d          dk     rd }|c|                    d          }|                      |d          }d }|dk    r|                      |d          }n|}|                     ||d          }|                     |d	i           }|                     |d	|          }	|                     |	|          }
|
d
         }|
| j        |<   d|z   }|                    |
|           i }|
||<   |                    |d           d S |                     ||           d S )Nr   contractMarketr   r   ry   allsubject-ra   r   r   r   )	rm   findsplitsafe_marketrU   parse_tickerr   resolvehandle_contract_ticker)rL   ro   r   r   r   partsfirstmarketIdra   	rawTickerr   r   r   
allTickerss                 rN   handle_tickerzkucoin.handle_ticker:  s\   T   '22::&''!++F C((((22E>>#//CCHH$H))(FC@@>>'6266DtVT::I&&y&99FH%F#)DL #f,KNN6;///!J!'JvNN:y11111''88888rO   c                    |                      |di           }|                     |d          }|                     |d d          }|                     ||          }|| j        |d         <   d|d         z   }|                    ||           d S )Nra   r   r   r   )rU   rm   r   r   r   r   )rL   ro   r   ra   r   r   r   r   s           rN   r   zkucoin.handle_contract_ticker  s    , ~~gvr22##D(33!!(D#66""400)/VH%&&"22v{+++++rO   c                 R  K   |                                   d{V  |                     |dddd          }|                     |          }|d         }d}|rd}|                     d|||           d{V }| j        ri }|||d         <   |S |                     | j        d|          S )	a  

        https://www.kucoin.com/docs-new/3470067w0
        https://www.kucoin.com/docs-new/3470080w0

        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>`
        NFTr   z/spotMarket/level1:z/contractMarket/tickerV2:r#   r   )r   r   r   watch_multi_helperr   r   bidsasks)rL   r   r[   r   rZ   channelNamer   r   s           rN   watch_bids_askszkucoin.watch_bids_asks  s       !!!!!!!!!%%gtUD%HH227;;%j1+ 	65K..WV\]]]]]]]]? 	G(.GF8$%N##DM8WEEErO   r   c                   K   |                                   d {V  |                     |d ddd          }t          |          }|dk    rt          | j        dz   |z   dz             g }t          dt          |                    D ]=}||         }|                     |          }	|                    d|	d         z              >|                     d           d {V }
| 	                    |          }d	
                    |          }t          |                                           }|d
||z   dd}|                     ||          }|                     |
|||           d {V S )NFTd    z#() accepts a maximum of 100 symbolsr   bidask@r   r   r   r   )r   r   r   r   r   r   r   r   r^   r   r   r   r}   r   r   )rL   
methodNamer   r   r[   lengthr   r   r   r   r   r   joinedrx   r   r   s                   rN   r   zkucoin.watch_multi_helper  s     !!!!!!!!!%%gtUD%HHWC<<#DGcMJ$>Af$fgggq#g,,'' 	? 	?AQZF[[((F  VH-=!=>>>>NN5))))))))OOG,,	)$$))**	 6)	
 
 ++gv..((mWmTTTTTTTTTrO   c                     |                      |          }|d         }|| j        |<   d|z   }|                    ||           d S )Nr   r   )parse_ws_bid_askr   r   )rL   ro   r   parsedTickerr   r   s         rN   handle_bid_askzkucoin.handle_bid_ask  sQ    : ,,W55h' ,f&(|[11111rO   c                    |                      |d          }|                    d          dk     r&|                    d          }|d         }|                     ||          }|                      |d          }|                     |di           }|                     |dg           }|                     |d	g           }	|                     |d
          }
|                     ||
|                     |
          | 	                    |d          | 	                    |d          | 	                    |	d          | 	                    |	d          |d|          S |                     |di           }|                      |d          }|                     ||          }|                      |d          }| 
                    |dd          }
|                     ||
|                     |
          | 	                    |d          | 	                    |d          | 	                    |d          | 	                    |d          |d|          S )Nr   r   r   r   ry   r   ra   asksbids	timestamp)r   r   datetimeask	askVolumebid	bidVolumeinfotsư>bestAskPricebestAskSizebestBidPricebestBidSize)rm   r   r   r   rU   rk   rl   safe_tickeriso8601safe_numbersafe_integer_product)rL   r   r   r   r   r   r   ra   r   r   r   s              rN   r   zkucoin.parse_ws_bid_ask  sJ     11::&''!++KK$$EQxH%%h77F%%fh77F>>&&"55D..vr22C..vr22C))$<<I## & LL33''Q//!--c155''Q//!--c155	% 	% 	 	 	 >>&&"55D''h77H%%h77F%%fh77F11$hGGI## & LL33''n==!--dMBB''n==!--dMBB	% 	% 	 	 	rO   1m	timeframesincelimitc                   K   |                                   d{V  |                     |          }|d         }|d         }|                     d|           d{V }|                     | j        ||          }	d}
|rd}
|
|d         z   dz   |	z   }d	|z   d
z   |z   }|                     ||||           d{V }| j        r|                    ||          }|                     |||dd          S )a  
        watches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://www.kucoin.com/docs-new/3470071w0
        https://www.kucoin.com/docs-new/3470086w0

        :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
        Nr   r   F/market/candles:/contractMarket/limitCandle:r   _candles:r   r   T)	r   r   r^   rm   
timeframesr   r   getLimitfilter_by_since_limit)rL   r   r   r   r   r[   r   rZ   r   periodr   r   r   ohlcvs                 rN   watch_ohlcvzkucoin.watch_ohlcv7  s/      !!!!!!!!!V$$! ,NN5/::::::::!!$/9iHH( 	98KfTl*S069 6)C/);nnS+ufEEEEEEEE? 	2NN6511E))%q$GGGrO   c                   K   |                                   d{V  |                     |          }|d         }|d         }|                     d|           d{V }d}|rd}|                     | j        ||          }||d         z   dz   |z   }	d	|z   d
z   |z   }
d|z   d
z   |z   }||g}|
|	g||	gdd|g|gd}|                     ||
|	|
||           d{V S )a*  
        unWatches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://www.kucoin.com/docs-new/3470071w0
        https://www.kucoin.com/docs-new/3470086w0

        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        Nr   r   Fr  r  r   r  zunsubscribe:candles:r   r  r	  T)r   r   r   r   r   symbolsAndTimeframes)r   r   r^   rm   r  r   )rL   r   r   r[   r   rZ   r   r   r  r   r   r   symbolAndTimeframer   s                 rN   un_watch_ohlcvzkucoin.un_watch_ohlcvU  sN      !!!!!!!!!V$$! ,NN5/::::::::( 	98K!!$/9iHHfTl*S069,v5;iG#f,s2Y>$i0
 *51!/ 7x%7$8

 

 &&sKVUabbbbbbbbbrO   c           	      "   |                      |di           }|                     |d          }|                     |dg           }|                     |d          }|                    d          }|                     |d          }|                     |          }	|                     |          }
|
d         }d|z   dz   |	z   }|                     | j        |i           | j        |<   |                     | j        |         |	          }|;|                     | j	        d	d
          }t          |          }|| j        |         |	<   |                    d          dk    }|rdnd}|                     |d          |                     |d          |                     |d          |                     |d          |                     |d          |                     ||          g}|                    |           |                    ||           d S )Nra   r   candlesr   r  ry   r  r   
OHLCVLimitr5   r   r      r8   r9         )rU   rm   rk   r   find_timeframer   rV   ohlcvsrl   rG   r   r   safe_timestampr   r   r   )rL   ro   r   ra   r   r  r   r   intervalr   r   r   r   storedr   isContractMarketbaseVolumeIndexparseds                     rN   handle_ohlcvzkucoin.handle_ohlcv{  s   R ~~gvr22##D(33..y"55  '22C  ##E1--''11	!!(++! 6)C/);"oodk62FFFV!4i@@>%%dlL$GGE*511F-3DK	*!JJ'788A=/6!!Q++Wa((Wa((Wa((Wa((Wo66
 	fv{+++++rO   c                 D   K   |                      |g|||           d{V S )a@  
        get the list of most recent trades for a particular symbol

        https://www.kucoin.com/docs-new/3470072w0
        https://www.kucoin.com/docs-new/3470084w0

        :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)rL   r   r   r   r[   s        rN   watch_tradeszkucoin.watch_trades  s6       22F8UE6RRRRRRRRRrO   c                 d  K   t          |          }|dk    rt          | j        dz             |                                  d{V  |                     |ddd          }|                     |          }|d         }|                     |          }|                     d|           d{V }	g }
g }d}|rd}|d	                    |          z   }t          dt          |                    D ]B}||         }|

                    d
|z              ||         }|
                    ||z              C|                     |	|
|||           d{V }| j        rB|                     |d          }|                     |d          }|                    ||          }|                     |||dd          S )a  
        get the list of most recent trades for a particular symbol

        https://www.kucoin.com/docs-new/3470072w0
        https://www.kucoin.com/docs-new/3470084w0

        :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 symbolsNFTr   /market/match:/contractMarket/execution:r   trades:r   r   )r   r   r   r   r   r   r   r^   r   r   r   r   r   rV   rm   r  r  )rL   r   r   r   r[   symbolsLengthr   rZ   r   r   r   r   r   r   r   r   r   tradesr   tradeSymbols                       rN   r  zkucoin.watch_trades_for_symbols  s      GA#DG.n$nooo!!!!!!!!!%%gtUDAA227;;%j1OOG,,	NN5/::::::::& 	76Kchhy111q#g,,'' 	> 	>AQZF  V!3444 |H%%kH&<====..sM5J\^deeeeeeee? 	8OOFA..E**5(;;KOOK77E))&%TRRRrO   c                   K   |                                   d{V  |                     |ddd          }|                     |          }|                     |          }|d         }|                     d|           d{V }g }g }d}	|rd}	|	d                    |          z   }
t          dt          |                    D ]:}||         }|                    d	|z              |                    d
|z              ;|                    |
           |                    |
           ||dd|d}| 	                    |||
|||           d{V S )a`  
        unWatches trades stream

        https://www.kucoin.com/docs-new/3470072w0
        https://www.kucoin.com/docs-new/3470084w0

        :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>`
        NFTr   r"  r#  r   r   zunsubscribe:trades:r$  r&  r   )
r   r   r   r   r^   r   r   r   r   r   )rL   r   r[   r   r   rZ   r   r   r   r   r   r   r   r   s                 rN   un_watch_trades_for_symbolsz"kucoin.un_watch_trades_for_symbols  s      !!!!!!!!!%%gtUDAAOOG,,	227;;%j1NN5/::::::::& 	76Kchhy111q#g,,'' 	: 	:AQZF  !6!?@@@%%i&&89999 	U###!!%(((* 2
 
 //]E=Z`bnooooooooorO   c                 @   K   |                      |g|           d{V S )a  
        unWatches trades stream

        https://www.kucoin.com/docs-new/3470072w0
        https://www.kucoin.com/docs-new/3470084w0

        :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)  rL   r   r[   s      rN   un_watch_tradeszkucoin.un_watch_trades"  s2       55vhGGGGGGGGGrO   c                    |                      |di           }|                     |d          }|                     |          }|                     ||          }|d         }d|z   }|| j        vr5|                     | j        dd          }	t          |	          }
|
| j        |<   | j        |         }|                    |           |	                    ||           d S )Nra   r   r$  rD   r5   )
rU   rm   r   parse_trader&  rl   rG   r   r   r   )rL   ro   r   ra   r   r   trader   r   r   r  caches               rN   handle_tradezkucoin.handle_trade/  s    ( ~~gvr22##D(33!!(++  v..x&($+%%%%dlM4HHE&&F"(DKF#Uuk*****rO   c                 B   K   |                      |g||           d{V S )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)rL   r   r   r[   s       rN   watch_order_bookzkucoin.watch_order_bookQ  s4      < 66xOOOOOOOOOrO   c                 @   K   |                      |g|           d{V S )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      rN   un_watch_order_bookzkucoin.un_watch_order_bookq  s2       996(FKKKKKKKKKrO   c                 $  K   t          |          }|dk    rt          | j        dz             |/|dk    r)|dk    r#|dk    r|dk    rt          | j        dz             |                                  d{V  |                     |          }|                     |          }|                     |          }|d	         }|                     d
|           d{V }|rdnd}	|rdnd}
| 	                    |d|
d|	          \  }	}|	
                    d          dk    r%|dk    s|dk    r|sd}	|	dt          |          z   z  }	|	dz   d                    |          z   }g }g }t          dt          |                    D ]E}||         }|                    d|z              ||         }|                    |	dz   |z              Fi }|	dk    s|	dk    r| j        ||d}|                     ||||||           d{V }|                                S )au  

        https://www.kucoin.com/docs-new/3470069w0  # spot level 5
        https://www.kucoin.com/docs-new/3470070w0  # spot level 50
        https://www.kucoin.com/docs-new/3470068w0  # spot incremental
        https://www.kucoin.com/docs-new/3470083w0  # futures level 5
        https://www.kucoin.com/docs-new/3470097w0  # futures level 50
        https://www.kucoin.com/docs-new/3470082w0  # futures incremental

        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 symbolsN   r   2   r8   z? watchOrderBook 'limit' argument must be None, 5, 20, 50 or 100r   Fr;   r:   r>   r6   r$   r   Depth/spotMarket/level2r   r   
orderbook:)r   r   r   )r   r   r   r   r   r   r   r   r^   r   r   r   r   r   r   handle_order_book_subscriptionr   r   )rL   r   r   r[   r%  r   r   rZ   r   r   
optionNamer   r   r   r   r   r   r   	orderbooks                      rN   r3  z#kucoin.watch_order_book_for_symbols  s       GA#DG.q$qrrr%3,,Ub[[uPQzz#DG.o$oppp!!!!!!!!!%%g..OOG,,	227;;%j1NN5/::::::::-<R))BR)8J%%l
88AQS]_giopp;;w2%%

& 21F'CJJ..sxx	222q#g,,'' 	? 	?AQZF  !6777 |H%%fslX&=>>>>&&&F6N,N,N=" L
 11#}eM_agiuvvvvvvvv	   rO   c                   K   |                      |d          }|                     |d          }|                                  d{V  |                     |ddd          }|                     |          }|                     |          }|d         }|                     d|           d{V }|rdnd}|rdnd	}	|                     |d
|	d|          \  }}|                    d          dk    r%|dk    s|dk    r|sd}|dt          |          z   z  }|dz   d
                    |          z   }
g }g }t          dt          |                    D ]:}||         }|                    d|z              |                    d|z              ;|                    |
           |                    |
           ||dd|d}|                     |||
|||           d{V S )aP  

        https://www.kucoin.com/docs-new/3470069w0  # spot level 5
        https://www.kucoin.com/docs-new/3470070w0  # spot level 50
        https://www.kucoin.com/docs-new/3470068w0  # spot incremental
        https://www.kucoin.com/docs-new/3470083w0  # futures level 5
        https://www.kucoin.com/docs-new/3470097w0  # futures level 50
        https://www.kucoin.com/docs-new/3470082w0  # futures incremental

        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' or '/contractMarket/level2' or '/contractMarket/level2Depth5' or '/contractMarket/level2Depth50' default is '/market/level2' for spot and '/contractMarket/level2' for futures
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/?id=order-book-structure>` indexed by market symbols
        r   NFTr   r;   r:   r>   r6   r$   r   r;  r<  r8   r:  r=  r   r   r   zunsubscribe:orderbook:r>  rA  )r   r   r   r   r   )rl   omitr   r   r   r   r^   r   r   r   r   r   r   r   r   )rL   r   r[   r   r   r   rZ   r   r   r@  r   r   r   r   r   r   s                   rN   r6  z&kucoin.un_watch_order_book_for_symbols  sJ       !!&'2267++!!!!!!!!!%%gtUDAAOOG,,	227;;%j1NN5/::::::::-<R))BR)8J%%l
88AQS]_giopp;;w2%%

& 21F'CJJ..sxx	222q#g,,'' 	= 	=AQZF  !9F!BCCC%%lV&;<<<< 	U###!!%(((*  2
 
 //]E=Z`bnooooooooorO   c                    |                      |d          }|                     |d          }|                    d          }|                     |d          }|                     |d          }|                     |d|          }|                     |d d          }	d|	z   }
|                    d	          dk    rY|	| j        vr|                                 | j        |	<   n!| j        |	         }|                                 |	| j        |	         d<   n}|	| j        vr|                                 | j        |	<   | j        |	         }|                     |d
          }| 	                    |dd          }|t          |j                  }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 |                     | j        |	         |           |                    | j        |	         |
           d S )Nra   r   r   ry   r   r   r   r>  r;  noncesequenceEndr   r   r$   r<   r8   )rU   rm   r   safe_symbolr   
orderbooks
order_bookresetrl   safe_integer_2r   r0  listr   keysr   handle_optionrW   load_order_bookr   handle_deltar   )rL   ro   r   ra   r   
topicPartstopicSymboltopicChannelr   r   r   rA  rE  deltaEndcacheLengthr   r   r   keyr   r<   s                        rN   handle_order_bookzkucoin.handle_order_book  s   R ~~gv..  '22[[%%
&&z155''
A66##D(K@@!!(D#66"V+::g!##do--*.//*;*;'' OF3	!!!06DOF#H--do--*.//*;*;'/I%%i99E**4LLH}!)/22 $V%9%>%>%@%@ A A#q#m"4"455  A'*C--22,9O9OST9T9T'-';C'@)),@@ $ 2 23C_VW X X-//JJt3V[&RWY[\\\&&t,,,(""$/&14888tv.<<<<<rO   c                    |                      |d          }|                     |d          }|                     |dd          }||dz
  k     rdS t          dt	          |                    D ]K}||         }|                     |dd          }|                     |dd          }	||dz
  k    r
||	k     r|c S Lt	          |          S )	Nr   rE  sequenceStartsequencery   r<  rF  r   )rV   rl   rK  r   r   )
rL   rA  r0  
firstDeltarE  firstDeltaStartr   delta
deltaStartrT  s
             rN   get_cache_indexzkucoin.get_cache_index?  s    __UA..
!!)W55--j/:VV?Q&&&2q#e**%% 	 	A!HE,,UOZPPJ**5-MMHa''eh.>.>5zzrO   c                    |                      |dd          }|                      |dd|          |d<   ||d<   |                     |          |d<   |                     |d          }|d         }|d	         }||                    d
          }|                     |d          }|                     |d          }	|                     |d          }
|	dk    rdnd	}||
g}|dk    r|                    |           d S |                    |           d S |                     |d|          }|                     |dg           }|                     |d	g           }|                     ||           |                     ||           d S )Ntimer   rF  rZ  rE  r   changer   r   r   r   ry   r  buychanges)	rK  r   rm   r   r   
storeArrayrU   rk   handle_bid_asks)rL   rA  r]  r   rb  
storedBids
storedAskssplitChangepricesidequantityr   valuerd  r   r   s                   rN   rP  zkucoin.handle_deltaM  s   ''v{CC	!00zS\]]	'!*	+ $Y 7 7	*!!%22v&
v&
 ,,s++K$$[!44E##K33D''Q77H"emm66&DH%Ev~~%%e,,,,,%%e,,,,,nnUIu==G>>'6266D>>'6266D  T222  T22222rO   c                     t          dt          |                    D ]2}|                     ||                   }|                    |           3d S Nr   )r   r   parse_bid_askre  )rL   bookSidebidAsksr   bidAsks        rN   rf  zkucoin.handle_bid_asksh  sY    q#g,,'' 	( 	(A''
33F''''	( 	(rO   c                 Z   |                      |d          }|                     |d          }|6|                     |d          }|                     i |          | j        |<   d S t          dt          |                    D ](}||         }|                     i |          | j        |<   )d S )Nr   r   r   r   )rl   rk   rm   rI  rH  r   r   )rL   ro   r   r   r   r   r   r   s           rN   r?  z%kucoin.handle_order_book_subscriptionm  s    !!,88..y99?%%lH==F&*oob%&@&@DOF###1c'll++ E E *.//"e*D*D''E ErO   c                 X   |                      |d          }||j        vrd S |                      |j        |          }|                     |j        |          }|j        |= |                     |d          }| ||||           |                     |dd          }|r|                     |dg           }|                     |dg           }	t          dt          |                    D ])}
||
         }|	|
         }|                     |||           *|                     |           d S d S )Nr   r   r   Fr   r   r   )	rm   r   rV   	safe_boolrk   r   r   clean_unsubscriptionclean_cache)rL   ro   r   r   r   r   r   isUnSubr   r   r   r   subHashs                rN   handle_subscription_statusz!kucoin.handle_subscription_status|  sT    gt,,f***F++F,@"EEv';=MNN $x88F67L111..}eDD 	+ NN<"MMM#~~l<NPRSS1c-0011 H H+A.*1-))&';GGGG\*****	+ 	+rO   c                     |S r    rL   ro   r   s      rN   handle_system_statuszkucoin.handle_system_status  s	     rO   c           	        K   |                                   d{V  |                     |dd          }|                     |ddg          }d}d}|%|                     |          }|d         }|dz   |z   }d}|                     d||          \  }}|dk    o|d	k    }	|                     d
|	           d{V }
|rdnd}|	r|rdnd}||                     |          }||z  }dd
i}|                     |
|||                     ||                     d{V }| j	        r|
                    ||          }|                     ||||d
          S )a  
        watches information on multiple orders made by the user

        https://www.kucoin.com/docs-new/3470074w0  # spot regular orders
        https://www.kucoin.com/docs-new/3470139w0  # spot trigger orders
        https://www.kucoin.com/docs-new/3470090w0  # contract regular orders
        https://www.kucoin.com/docs-new/3470091w0  # contract trigger orders

        :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
        :param str [params.type]: 'spot' or 'swap'(default is 'spot' if symbol is not provided)
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nstoptriggerordersr   r   r%   r   r   T/spotMarket/advancedOrdersr?   /contractMarket/advancedOrders/contractMarket/tradeOrdersrY   )r   safe_bool_2rC  r   r   r^   get_orders_message_hash_suffixr   r   r   r  filter_by_symbol_since_limit)rL   r   r   r   r[   r  r   r   r   rZ   r   r   suffixr   r  s                  rN   watch_orderszkucoin.watch_orders  s     " !!!!!!!!!""669==6FI#677[[((FH%F%+f4K
!??vW]^^
F&&0NzX7MNN49999999907V,,=V 	c8?b44EbE>88??F6!Kd
 ~~c;t{{7TZ?[?[\\\\\\\\? 	3OOFE22E00tTTTrO   c                 D    d}|dk    r|dz  }n|dk    rd}n|dk    rd}|S )N-spotr  z-triggerr  	-contractr  z-contract-triggerr}  rL   r   r  s      rN   r  z%kucoin.get_orders_message_hash_suffix  sH    000j FF333 FF666(FrO   c                 D    dddddddd}|                      |||          S )Nopenclosedcanceled	triggered)r  filledmatchupdater  cancel	TRIGGERED)rm   )rL   statusstatusess      rN   parse_ws_order_statuszkucoin.parse_ws_order_status  s=    " $
 
 &&999rO   c           	         |                      |d          }|                     |          }|                     |dd          }|                      |d          }|                     ||          }|d         r|                     |dd          }|                      |d          }|                     |d          }|d	uo|d u}	|d
k    r|	rd}|                     i d|d|d         d|                      |d          d|                      |d          d|d|                     |          dd d|                     |d          dd dd d|                     |d          d| 	                    |dd          d|d|d|                      |d          dd dd |                      |d          d |d d d |          S )!Nr   	orderTime	createdAtr   r   r   	stopPricetriggerSuccessTr  r  r   r   orderIdclientOrderId	clientOidr   r   lastTradeTimestamp	orderTypetimeInForcepostOnlyrk  rj  
orderPricetriggerPriceamountsizecostaverage
filledSize)r  	remainingr  feer&  )
rm   r  rK  r   r   rv  
safe_orderr   safe_string_lowersafe_string_2)
rL   orderr   rawTyper  r   r   r  r  triggerFails
             rN   parse_ws_orderzkucoin.parse_ws_order  sp   @ ""5&11++G44''{KHH	##E844!!(F33* 	P11%hOOI''{;;/?@@%T1Sd8Rk!!{!F  
E 
fX& 
 $""5)44 
 T--e[AA	 

  
 Y// 
 !$ 
 D**5+>> 
 4 
  
 D**5&99 
 T''wEE 
  
 L 
 d&&uf55 
  D! 
" t# 
$ &&ul;;- 
  
  
. /  	rO   c                 z   |                      |d          }|                     |d          }||                     ||           |                     |          }|                     |d          }|                     |d          }|                     |d          }|d u}	| j        D|                     | j        dd          }
t          |
          | _        t          |
          | _        |	r| j        n| j        }| 	                    |j
        |i           }| 	                    ||          }||d         d	k    rd	|d<   |                    |           d
}|                     |d          }|                     |          }||z   }|                    ||           |dz   |z   }|                    ||           d S )Nra   tradeIdr   r   r  ordersLimitr5   r  r  r  r   r   )rU   rm   handle_my_trader  r  rl   rG   r   triggerOrdersrV   hashmapr   r  r   )rL   ro   r   ra   r  r  r   r  r  isTriggerOrderr   cachedOrdersr  r  r   r   r  typeSpecificMessageHashsymbolSpecificMessageHashs                      rN   handle_orderzkucoin.handle_orderJ  s   * ~~gv..""433  111$$T**!!&(33""6400''??&d2;%%dlM4HHE077DK!7!>!>D-;Lt))!5vrBB00X(**#+x F###  '2244U;;"-"6|%<===$/#$5$>!|%>?????rO   c           	        K   |                                   d{V  d}d}|+|                     |          }|d         }|dz   |d         z   }d}|                     d||          \  }}|dk    o|dk    }|                     d|           d{V }	|rd	nd
}
|rdnd}|                     |d|d|
          \  }
}ddi}||                     |
          }||z  }|                     |	||
|                     ||                     d{V }| j        r|	                    ||          }| 
                    ||||d          S )a  
        watches information on multiple trades made by the user on spot

        https://www.kucoin.com/docs-new/3470074w0
        https://www.kucoin.com/docs-new/3470090w0

        :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' or '/contractMarket/tradeOrders', default is '/spotMarket/tradeOrders'
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=trade-structure>`
        NmyTradesr   r   r(   r   r   Tr  r?   r>   r6   r   rY   )r   r   r   r^   r   !get_my_trades_message_hash_suffixr   r   r   r  r  )rL   r   r   r   r[   r   r   r   rZ   r   r   r@  r   r  r&  s                  rN   watch_my_tradeszkucoin.watch_my_trades|  s      !!!!!!!!! [[((FH%F%+fX.>>K
!??QWY_``
F&&0NzX7MNN4999999991@_--F_)8J%%l
77Q[]eglmmvd
 >;;EBBF6!K~~c;t{{7TZ?[?[\\\\\\\\? 	3OOFE22E00tTTTrO   c                 @    d}|                     d          dk    rd}|S )Nr  r   r   r  )r   r  s      rN   r  z(kucoin.get_my_trades_message_hash_suffix  s)    ::&''1,, FrO   c                    | j         0|                     | j        dd          }t          |          | _         |                     |d          }|                     |          }| j         }|                    |           d}|                     |d          }|                     |          }	||	z   }
|	                    | j         |
           |dz   |d         z   }|	                    | j         |           d S )NrD   r5   ra   r  r   r   r   )
r  rl   rG   r   rU   parse_ws_trader   rm   r  r   )rL   ro   r   r   ra   r  r  r   r   r  r  r  s               rN   r  zkucoin.handle_my_trade  s    : = %%dlM4HHE2599DM~~gv..$$T**=   '2277>>"-"6t}&=>>>$/#$5x8H$H!t}&?@@@@@rO   c                    |                      |d          }|                     ||d          }|d         }|                      |d          }|                      |d          }|                      |d          }|                      |d          }|                      |d          }	|,|                      |d          }|                      |d	          }	|                      |d
          }
|                     |ddd          }|d         }|                      |d          }|                      |d          }|                     |||                     |          |||
||                      |d          |||	d |||dd|          S )Nr   r   r  rk  r  
matchPrice	matchSizerj  r  r  r   ra  r   quotefeeRater  	liquidity)r  ratecurrency)r   r   r   r   r   r  r   takerOrMakerrk  rj  r  r  r  )rm   r   safe_integer_product_2
safe_trader   )rL   r/  r   r   r   r   rk  r  rj  r  r  r   feeCurrencyr  feeCosts                  rN   r  zkucoin.parse_ws_trade  s   R ##E844!!(FC88!{33v..""5)44  55!!%55=$$UG44E%%eV44F  	22//tVXNN	Wo""5)44""5%00"Y// ,,UK@@'  
  
$ %  	rO   c                   K   |                                   d{V  |                     | j        dd          }|                     |d|          }|                     |d          }|                     | j        di           }|                     |||          }|dk    }|                     d|           d{V }|                     |          }|                     ||           |                     | j        d          }	|                     |	d	d
          }
|                     |	dd          }|
r |r|	                    |dz              d{V  |dz   }t          |                                           }|rdnd}|d|ddd}|                     ||          }||j        vr
||j        |<   |                     ||||           d{V S )a  
        watch balance and get the amount of funds available for trading or funds locked in orders

        https://www.kucoin.com/docs-new/3470075w0  # spot balance
        https://www.kucoin.com/docs-new/3470092w0  # contract balance

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.type]: 'spot' or 'swap'(default is 'spot')
        :returns dict: a `balance structure <https://docs.ccxt.com/?id=balance-structure>`
        NdefaultTyper   r   accountsByTyper   Tr.   r@   FrA   :fetchBalanceSnapshot:balance/contractAccount/walletz/account/balancer   )r   r   r   rs   rY   )r   rm   rG   rC  rU   r^   ro   set_balance_cacherv  r]   r   r}   r   r   r   )rL   r[   r  r   r  uniformTyperZ   r   ro   rG   r@   rA   r   rx   r   r   r   s                    rN   watch_balancezkucoin.watch_balance#  s      !!!!!!!!!&&t|]FKK<<66**6FKK&&~tTBB&*4NN499999999S!!v{333..~>>#~~g7MuUU#~~g7MtTT 	G$8 	G--.E EFFFFFFFFF!J.))**	8G_44M_%"
 
 ++gv.. F$888.>F +ZZ['4@@@@@@@@@rO   c                 2   ||j         v r|| j        v rd S |                     | j        d          }|                     |dd          }|rD|dz   }||j        vr4|                    |           |                     | j        |||           d S d S i | j        |<   d S )Nr.   r@   Fr  )	r   balancerU   rG   rv  futuresr]   rW   load_balance_snapshot)rL   ro   r   rG   r@   r   s         rN   r  zkucoin.set_balance_cacheL  s    F(((tt|/C/CF..~>>#~~g7MuUU 	$!88K6>11k***

45v{DQQQQQ 21 "$DLrO   c                 X  K   d|i}|                      |           d {V }|                     ||                     | j        |i                     | j        |<   ||j        v rG|j        |         }|                                 |                    | j        |         |dz              d S d S )Nr   r  )fetch_balancer   rV   r  r  r   )rL   ro   r   r   r[   rs   r]   s          rN   r  zkucoin.load_balance_snapshotY  s      D
 ++F33333333![[4??4<QUWY3Z3Z[[T&.((^K0FNNNN4<-tj/@AAAAA )(rO   c                    |                      |di           }|                     |d          }|                     |d          }d }|+|                    d          }|                     |d          }|                     |d          }|dk    rd}|                      | j        d	          }	|                     |	|d
          }
|
| j        vr
i | j        |
<   || j        |
         d<   |                     |dd          }|| j        |
         d<   |                     |          | j        |
         d<   |                     |          }|                                 }| 	                    |dd          }| 
                    |                     |d                    }|t          j        ||          }| 	                    |dd          |d<   ||d<   |                     |d          |d<   || j        |
         |<   |                     | j        |
                   | j        |
<   |
dz   }|                    | j        |
         |           d S )Nra   r  relationEvent.r   r   r  r   r  r/  r   ra  r   r   holdholdBalanceisolatedPosMargin	availableavailableBalancefreeusedtotalr  )rU   rm   r   rG   r  rK  r   safe_currency_codeaccountr  	omit_zeror   
string_addsafe_balancer   )rL   ro   r   ra   
currencyIdr  requestAccountTyperelationEventPartsr   r  r  r   coder  r  r  r   s                    rN   handle_balancezkucoin.handle_balancee  sN   H ~~gvr22%%dJ77
((??!$!.!4!4S!9!9!%!1!12Da!H!H  '22---!+6FGG&&~7I7SSt|++(*DL%,0[!&)''fkBB	1:[!+.04Y0G0G[!*-&&z22,,..!!$>> NN4+;+;DBU+V+VWW(%d,=>>D,,T;@RSS++D'::*1[!$'$($5$5dl;6O$P$P[!!J.t|K0+>>>>>rO   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{V S )ah  
        watch open positions for a specific symbol

        https://www.kucoin.com/docs-new/3470093w0

        :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   rY   	position:r   r&   rB   rC   fetchPositionSnapshot:)r   r   r   r^   r   ro   set_position_cacherN  get_current_positionr]   r   r   )rL   r   r[   r   r   r   r   r   ro   rB   rC   currentPositionsnapshots                rN   watch_positionzkucoin.watch_position  s      >#DG.[$[\\\!!!!!!!!!NN4((((((((V$$%t4d
 "F8$44S!!/// $ 2 2?D[]a b b $ 2 2?D[]a b b33F;;  	%: 	?V#]]+Cf+LMMMMMMMMHO^^CeT[[RX=Y=YZZZZZZZZZrO   c                     | j         d S | j         j        }|                     ||i           }t          |                                          }|                     |d          S ro  )	positionsr  rV   rL  values)rL   r   r0  symbolCacher  s        rN   r   zkucoin.get_current_position  s[    >!4&ooeVR88k((**++vq)))rO   c                     |                      ddd          }|rBd|z   }||j        vr6|                    |           |                     | j        |||           d S d S d S )Nr&   rB   Fr  )rN  r  r]   rW   load_position_snapshot)rL   ro   r   rB   r   s        rN   r  zkucoin.set_position_cache  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1rO   c                 *  K   |                      |           d {V }t                      | _        | j        }|                    |           ||j        v r=|j        |         }|                    |           |                    |d|z              d S d S )Nr  )fetch_positionr   r  r   r  r   )rL   ro   r   r   positionr0  r]   s          rN   r	  zkucoin.load_position_snapshot  s      ,,V44444444/11X&.((^K0FNN5!!!NN8[6%9::::: )(rO   c                 |   |                      |dd          }|                    d          }|                      |d          }|                     |d d          }| j        }|                     |          }d|z   }	|                     |di           }
|                     |
          }t          |                                          }t          dt          |                    D ]}||         }||         ||= |                     ||          }|                    |           |                    ||	           d S )Nr    r   ry   r  ra   r   )rm   r   rG  r  r   rU   parse_positionrL  rM  r   r   r   r   r   )rL   ro   r   r   r   r   r   r0  r  r   ra   newPositionrM  r   rV  r  s                   rN   handle_positionzkucoin.handle_position  s9   z   '266C  ##E1--!!(D"5533F;;!F*~~gvr22))$//K$$&&''q#d))$$ 	% 	%Aq'C3'$;;<<Xx-----rO   c                 <   |                      |d          }|dk    r|                     ||           d S |                      |d          }i d| j        d| j        d| j        d| j        d| j        d	| j        d
| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        | j        | j        | j	        | j	        | j	        d}| 
                    ||          }| |||           d S d S )Nr   z/market/ticker:allr   level1level2ztrade.l2updateztrade.tickerztrade.snapshotztrade.l3matchztrade.candles.updatezaccount.balanceorderChange	stopOrderz/spot/tradeFillsr   tickerV2zcandle.stickr  orderUpdatedsymbolOrderChange)zavailableBalance.changezwalletBalance.changezposition.changezposition.settlementzposition.adjustRiskLimit)rm   r   r   rW  r1  r  r  r  r  r  rV   )rL   ro   r   r   r   methodsr   s          rN   handle_subjectzkucoin.handle_subjectq  s   "   '22(((vw///F""7I66
d)
d,
 d4
 D.	

 d0
 T.
 #D$5
 t2
 4,
 *
  4
 d(
 +
 D-
  T&!
" D-#
$  !2%
& (,':$($7#3#'#7(,(</
 
 
2 '22F67##### rO   c                 N    t          |                                           }|ddS )NrE   )r   r   )r   r}   )rL   ro   r   s      rN   rE   zkucoin.ping  s0     ""##
 
 	
rO   c                 8    |                                  |_        d S r   )millisecondslastPongr~  s      rN   handle_pongzkucoin.handle_pong  s    ++--rO   c                     |                      |dd          }|dk    r2d}|j                            d          dk    rd}d | j        d         |<   |                     d	d|j        di ||i i 	  	         d
S )Nra   r  ztoken is expiredrR   zconnectId=privater   rQ   rT   ry   F)rm   r   r   rG   handle_errors)rL   ro   r   ra   r   s        rN   handle_error_messagezkucoin.handle_error_message  s     44%%%Dz233q88 )-DL &1b&*b"dGRLLLurO   c                     |                      |d          }| j        | j        | j        | j        | j        d}|                     ||          }| |||           d S d S )Nr   )welcomeackr   pongerror)rm   r  r{  r  r   r#  rV   )rL   ro   r   r   r  r   s         rN   handle_messagezkucoin.handle_message  s~    00 02*$.
 
 $//F67##### rO   elementNamec                      ||dz   |z   S |dz   S )Nr   zs@allr}  )rL   r*  r   s      rN   get_message_hashzkucoin.get_message_hash  s%     $v--((rO   r   )Q__name__
__module____qualname__r   rK   r^   rX   r}   r   dictr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r	   r   rL  r
  r  r  r   r   r  r)  r,  r1  r   r4  r7  r3  r6  rW  r_  rP  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  rE   r   r   r#  r)  r,  __classcell__)rM   s   @rN   r   r      sQ	       ;# ; ; ; ; ; ;z ?DB      HJ . . . .`   JLZ^ [ [ [ [ TVlp u uei u u u u ^`nr h h h h  acy} h hrv h h h h$ 68 E E EF E E E E2 9; "f "fC "fv "f "f "f "fH 6:" 2E 2E7 2E 2E 2E 2E 2Ehb9F b9 b9 b9 b9H,V , , , ,< 8<B F FW F7 F F F F2 Y]eg U U Ug U U U U0!2V !2 !2 !2 !2F% % % %N ?CQUdhqs H H H H3 H^a Hx|  ~B  yC H H H H< BFb $c $c3 $c3 $cUYZ^U_ $c $c $c $cLE,6 E, E, E, E,N <@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P LN 'p 'pc 'pRU 'p 'p 'p 'pR 9; H HC Hs H H H H +6  +  +  +  +D @DB P PS P PS\ P P P P@ =? L L L3 L L L L  SW_a 4! 4!$s) 4!C 4!fo 4! 4! 4! 4!l PR 3p 3pT#Y 3pVY 3p 3p 3p 3pjQ= Q= Q= Q= Q=f  3 3 36( ( (
	EV 	E 	E 	E 	E+ + + + +46     04$UYbd *U *U *UC *Us *Uimnsit *U *U *U *UX  
: 
: 
:c c c cJ0@6 0@ 0@ 0@ 0@d 37TX\eg %U %UC %Us %URU %Ulpqvlw %U %U %U %UN  *Af *A *A *A *AXL L L L\ *, 'A 'A 'A 'A 'A 'AR$ $ $ $ $
B 
B 
Bb?V b? b? b? b?H 26b [ [3 [X [ [ [ [<* * *U U U U U U	; 	; 	;m.f m. m. m. m.^1$V 1$ 1$ 1$ 1$f
6 
 
 
 
.& . . . .6 t    $$V $ $ $ $) )C ) ) ) ) ) ) ) ) )rO   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   r   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   r   ccxt.base.preciser   async_supportr   r}  rO   rN   <module>r;     s#       f f f f f f f f f f v v v v v v v v v v v v v v v v v v v v v v v v v v v v 4 4 4 4 4 4       * * * * * * . . . . . . % % % % % %H) H) H) H) H)T& H) H) H) H) H)rO   