
    iJ                       d dl mZ d dlmZ d dlZd dlZd dlZd dlZd dlm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ d dlmZ d dlm Z  d dlm!Z! d dlm"Z" d d	lm#Z# d d
lm$Z$ d dlm%Z% d dlm&Z& d dlm'Z' d dlm(Z( d dlm)Z) d dlm*Z* d dlm+Z+ d dlm,Z, d dlm-Z- d dlm.Z. d dl/m0Z0 d dl/m1Z1 d dl2m3Z3  G d dee          Z4dS )    )Exchange)ImplicitAPIN)AccountBalances
CurrenciesCurrencyIntMarketNumOrder	OrderBookOrderRequest	OrderSide	OrderTypeStrStringsTickerTickersTradeTradingFeeInterfaceTransactionTransferEntry)List)ExchangeError)AuthenticationError)PermissionDenied)AccountSuspended)ArgumentsRequired)
BadRequest)	BadSymbol)InsufficientFunds)InvalidAddress)InvalidOrder)OrderNotFound)NotSupported)RateLimitExceeded)ExchangeNotAvailable)InvalidNonce)TRUNCATE)	TICK_SIZE)Precisec                       e Zd Z fdZd Zi fdZi fdZi fdee         fdZ	i fde
fdZi fdee         fdZi fd	efd
Zi fd	efdZd^defdZd Zd^dedefdZdi fdedefdZi fdedefdZd^dedefdZdddi fdedededee         fdZi fd	efdZi fd	efdZd^defdZ i fd	efdZ!di fdedede"fdZ#d  Z$di fded!e%d"e&d#e'd$e(f
d%Z)i fded"e&d&e'fd'Z*i fded&e'fd(Z+i fded&e'fd)Z,i fd*ee-         fd+Z.defd,Z/di fded!e%d"e&d#e'd$e(f
d-Z0ddi fd.eded!e%d"e&d#e(d$e(fd/Z1di fd.ede2fd0Z3di fde2fd1Z4dddi fde2dedefd2Z5dddi fde2dededee6         fd3Z7dddi fde2dededee6         fd4Z8di fd.ede2fd5Z9d^dede6fd6Z:dddi fd.ede2dedefd7Z;dddi fde2dedefd8Z<ddi fdedededee=         fd9Z>d^dede=fd:Z?i fdede@fd;ZAdi fd	ed#e'fd<ZBd= ZCd^dedeDfd>ZEdddi fd	e2dededeeD         fd?ZFdddi fd	e2dededeeD         fd@ZGdA ZHi fdeIfdBZJi fd	ed#e'dCedDedeKf
dEZLd^defdFZMdG ZNdH ZOd^defdIZPdddi fd	e2dedefdJZQi fdKZRdL ZSd^defdMZTddddi fd	e2de2dedefdNZUd^defdOZVdddi fdedefdPZWddi fd	ededefdQZXdR ZYi fd	ed#e'fdSZZi fded	ed#e'fdTZ[i fd	efdUZ\i fded	efdVZ]d^defdWZ^di fdXefdYZ_dZd[i ddfd\Z`d] Za xZbS )_kucoinc                 8   |                      t          t          |                                           i ddddddgddd	d
dddddddddi dd ddddddddddddddddddddddddd dd!dd"dd#d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d0dd1dd2dd3dd4di d5dd6dd7dd8dd9dd:dd;dd<dd=dd>dd?dd@ddAddBddCddDddEdi dFddGddHddIddJddKddLddMddNddOddPddQddRddSddTddUddVdddddddddddddddddWdXdYdZd[d[d\d\d]d^d_d`dagdbdcddddddei dfdgdhdgdidjdkdldmdndodndpdgdqdjdrdldsdjdtdgdudgdvdgdwdgdxdgdydldzd{d|d}id~i ddddddddlddddddlddddndddddddd}dd}ddddddi ddddddddddddlddlddlddlddlddddddddddddddi ddddlddddlddddddddlddldddddddddddddddddd{ddddd}d}ddddddldi ddnddddddddddjdddd}ddddddœddœddœddœddœddldddddlddddddd}dd}d}ddd̜i ddddddœddœddœddœddddddddlddddddlddddlddlddldlddddԜd՜i ddgddgddlddgdddd}ddddgddddldydgddgddgddldddwdldxdjddid|d}id~i ddlddddddddlddddddddddddgdd}ddlddldd}dddddddldldgdjd}djdjd}d
ddddndd՜dddiiddddldddldldldddlid՜dddddd ddddddddd	d
ddt          di dt
          dt
          dt
          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          i dt          d t          d!t          d"t          d#t
          d$t          d%t          d&t          d't          d(t
          d)t          d*t          d+t          d,t          d-t          d.t          d/t          i d0t          d1t          d2t          d3t          d4t          d5t          d6t          d7t          d8t          d9t          d:t          d;t          d<t          d=t          d>t          d?t          d@t          i dAt          dBt          dCt          dDt          dEt          dFt          dGt          dHt          dIt          dJt          dKt          dLt          dMt          dNt          dOt          dPt          dQt          i dRt          dSt          dTt          dUt          dVt          dWt
          dXt          dYt          dZt          d[t          d\t          d]t          d^t          d_t          d`t          dat          dbt          i dct          ddt          det          dft           dgt          dht"          dit          djt          dkt          dlt          dmt          dnt          dot          dpt          dqt          drt          dst          t          t          t           t          t          t          t$          t          t          t          t          t          dtt          t          dudvdwdd|                     dx          |                     dx          |                     dy          |                     dx          g|                     dz          |                     dx          g|                     d{          |                     d|          g|                     d          |                     d}          g|                     d~          |                     d          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          gg|                     dy          |                     dx          g|                     dz          |                     d|          g|                     d{          |                     d          g|                     d          |                     d          g|                     d~          |                     d          g|                     d          |                     dy          g|                     d          |                     dy          g|                     d          |                     dy          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          ggddddi i dddddddddddddddiddidddd
dii dd
dddd
dd
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
dd
d
dddddddddddddddddddddiiddddddddddddddddddd
i ddddddddddddddddÓdĐdœdƐdǓdȐdɓdʐd˓d̐d͓dΐdϓdАdѓdҐdӓdԐdՓi d֐dדdؐdٓdڐdۓdܐdݓdސdߓddddddddddddddddddddddddi ddddddddd ddddddddd	d
dddddddddddddddi ddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;i d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]i d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdpdqdrdsdtdudvdwdxdydzd{d|d}d~i dddddddddddddddddddddddddddddddddddddddddddddddddddddddd          S (  Nidr-   nameKuCoin	countriesSC	rateLimit
   versionv2	certifiedTprocommentzPlatform 2.0quoteJsonNumbersFhasCORSspotmarginswapfutureoptionborrowCrossMarginborrowIsolatedMargincancelAllOrderscancelOrdercloseAllPositionsclosePositioncreateDepositAddresscreateMarketBuyOrderWithCostcreateMarketOrderWithCostcreateMarketSellOrderWithCostcreateOrdercreateOrderscreatePostOnlyOrdercreateStopLimitOrdercreateStopMarketOrdercreateStopOrdercreateTriggerOrder	editOrderfetchAccountsfetchBalancefetchBorrowInterestfetchBorrowRateHistoriesfetchBorrowRateHistoryfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositAddressfetchDepositAddressesByNetworkfetchDepositsfetchDepositWithdrawFeefetchDepositWithdrawFeesfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchL3OrderBookfetchLedgerfetchLeverageTiersfetchMarginAdjustmentHistoryfetchMarginModefetchMarketLeverageTiersfetchMarketsfetchMarkOHLCVfetchMyTrades
fetchOHLCVfetchOpenInterestfetchOpenInterestHistoryfetchOpenOrders
fetchOrderfetchOrderBookfetchOrderBooksfetchOrdersByStatusfetchOrderTradesfetchPositionModefetchPremiumIndexOHLCVfetchStatusfetchTickerfetchTickers)	fetchTimefetchTradesfetchTradingFeefetchTradingFeesfetchTransactionFeefetchTransfersfetchWithdrawalsrepayCrossMarginrepayIsolatedMarginsetLeveragesetMarginModesetPositionModesignIntransferwithdrawurlszdhttps://user-images.githubusercontent.com/51840849/87295558-132aaf80-c50e-11ea-9801-a2fb0c57c799.jpgz2https://www.kucoin.com/ucenter/signup?rcode=E5wkqezhttps://api.kucoin.comzhttps://api-futures.kucoin.comzhttps://kucoin.com/_apizhttps://api-broker.kucoin.com)publicprivatefuturesPrivatefuturesPublicwebExchangebrokerzhttps://www.kucoin.comzhttps://docs.kucoin.com)logoreferralapiwwwdocrequiredCredentials)apiKeysecretpasswordr   
currenciesg      @currencies/{currency}symbols   zmarket/orderbook/level1   zmarket/allTickersg     6@zmarket/statsmarketsz%market/orderbook/level{level}_{limit}zmarket/orderbook/level2_20zmarket/orderbook/level2_100zmarket/historieszmarket/candlesprices	timestampstatuszmark-price/{symbol}/currentzmargin/config   zbullet-public   )getpostz	user-info   accountsg      @zaccounts/{accountId}zaccounts/ledgerszhf/accounts/ledgers   zhf/margin/account/ledgersztransaction-historyzsub/userzsub-accounts/{subUserId}zsub-accountszsub/api-keyzmargin/account(   zmargin/accountszisolated/accountsdeposit-addressesdepositszhist-depositswithdrawalszhist-withdrawalszwithdrawals/quotaszaccounts/transferableztransfer-listzbase-feez
trade-feeszmarket/orderbook/level{level}zmarket/orderbook/level2zmarket/orderbook/level3zhf/orders/activezhf/orders/active/symbolszhf/orders/donezhf/orders/{orderId}z"hf/orders/client-order/{clientOid}zhf/orders/dead-cancel-all/queryzhf/fillsorderszlimit/ordersorders/{orderId}zorder/client-order/{clientOid}fillszlimit/fills   
stop-order   zstop-order/{orderId}z stop-order/queryOrderByClientOidoco/order/{orderId}zoco/order/details/{orderId}oco/client-order/{clientOid}
oco/orderszhf/margin/orders/active   zhf/margin/orders/donehf/margin/orders/{orderId})hf/margin/orders/client-order/{clientOid}   2   )hf/margin/fillsetf/infomargin/currencieszrisk/limit/strategyzisolated/symbolszisolated/account/{symbol}margin/borrowmargin/repaymargin/interestproject/listproject/marketInterestRateredeem/orderspurchase/orderszbroker/api/rebase/downloadsub/user/createdzsub/api-key/update-   accounts/universal-transferaccounts/sub-transferaccounts/inner-transfertransfer-outtransfer-inz	hf/orders   zhf/orders/testzhf/orders/synczhf/orders/multizhf/orders/multi/synczhf/orders/alterzhf/orders/dead-cancel-all)r   orders/testorders/multir   	oco/orderhf/margin/orderhf/margin/order/testzmargin/orderzmargin/order/testr   r   purchaseredeemlend/purchase/updatebullet-privatezwithdrawals/{withdrawalId}zhf/orders/sync/{orderId}z'hf/orders/sync/client-order/{clientOid}zhf/orders/cancel/{orderId}zhf/orders/cancelAllz!stop-order/cancelOrderByClientOidzstop-order/cancel)r   r   r   hf/margin/orders)r   r   deletezcontracts/activezcontracts/{symbol}tickerzlevel2/snapshotzlevel2/depth20zlevel2/depth100ztrade/historyzkline/queryzinterest/queryzindex/queryzpremium/queryztrade-statisticszfunding-rate/{symbol}/currentzcontract/funding-rateszlevel2/message/queryg&S?zaccount-overviewzaccount-overview-all	   
stopOrdersrecentDoneOrderszorders/byClientOidrecentFillsopenOrderStatisticsposition	positionszmargin/maxWithdrawMarginzcontracts/risk-limit/{symbol}zfunding-history)
r   r   r   r   r   z#position/margin/auto-deposit-statuszmargin/withdrawMarginzposition/margin/deposit-marginz position/risk-limit-level/changer   g      ?)r   zorders/client-order/{clientOid}r   r   r   zcurrency/currency/chain-info)zbroker/nd/infobroker/nd/accountbroker/nd/account/apikeyzbroker/nd/rebase/download)zbroker/nd/transferr   r   zbroker/nd/account/update-apikeyr   )r   r   r   r   r   r   
timeframes1min3min5min15min30min1hour2hour4hour6hour8hour12hour1day1week1month)1m3m5m15m30m1h2h4h6h8h12h1d1w1MprecisionMode
exceptionszorder not existzorder not exist.order_not_exist&order_not_exist_or_not_allow_to_cancelz)Order size below the minimum requirement.z7The withdrawal amount is below the minimum requirement.z8Unsuccessful! Exceeded the max. funds out-transfer limitz The amount increment is invalid.400401403404405415429500503101030103000130101130102130103130104130105130106130107130108130201130202130203130204130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315126000126001126002126003126004126005126006126007126009126010126011126013126015126021126022126027126028126029126030126033126034126036126037126038126039126041126042126043126044126045126046126047126048135005135018200004210014210021230003260000260100300000400000400001400002400003400004400005400006400007400008400100400200400350400370400400)400401400500400600400760401000408000411100415000400303500000260220900014)zExceeded the access frequencyzrequire more permission)exactbroadfeesz0.001050200z0.0009z0.00081000z0.000720004000z0.00068000z0.000515000z0.0004525000z0.000440000z0.0003560000z0.000380000z0.00025z-0.00005)takermaker)	tierBased
percentager  r  tiers)r  r  r   deposit)tradingfundingBIFIFVAIOTWAXP)BIFIVAIWAXv1-private_get_fills)webApiEnablewebApiRetrieswebApiMuteFailurefetchTickersFees
includeFeeGETv3)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  POSTDELETEr  )r   r   r   ccxtz$9e58cc35-5b5e-4133-92ec-166e3f077cb8)r/   keyccxtfuturesz$1b327198-f30c-4f14-a0ac-918871282f15)r>   rA   tradeisolatedmaincontractpooltrade_hf)
r>   r?   crossr  r  r  rA   r@   mininghfBTCbtcBTCNATIVESEGWITbech32ERC20ethTRC20trxHRC20hecoMATICmaticKCCkccSOLsolALGOalgoEOSeosBEP20bscBEP2bnbARBONEarbitrumAVAXXavaxAVAXCavaxcTLOStlosCFXcfxACAacaOPTIMISMoptimismONTontGLMRglmrCSPRcsprKLAYklayXRDxrdRVNrvnNEARnearAPTaptosETHWethwTONtonBCHbchBSVbchsvBCHAbchabcOSMOosmoNANOnanoXLMxlmVETvetIOSTiostZILzilXRPxrpTOMOtomoXMRxmrCOTIcotiXTZxtzADAadar  waxpTHETAthetaONEoneIOTEXiotxNULSnulsKSMksmLTCltcWAVESwavesDOTdotSTEEMsteemQTUMqtumDOGEdogeFILfilXYMxymFLUXfluxATOMatomXDCxdcKDAkdaICPicpCELOceloLSKlskVSYSvsysKARkarXCHxchFLOWflowBANDbandEGLDegldHBARhbarXPRxprARarFTMftmKAVAkavaKMAkmaXECxecIOTAiotaHNThntASTRastrPDEXpdexMETISmetisZECzecPOKTpoktOASYSoasOASISoasisETCetcAKTaktFSNfsnSCRTscrtCFGcfgICXicxKMDkmdNEMSTXstxDGBdgbDCRdcrCKBckbELAelaHYDRAhydraBTMbtmKARDIAkaiSXPsxpNEBLneblZENzenSDNsdnLTOltoWEMIXwemixEVEReverBNCbncBNCDOTbncdotAIONaionGRINgrinLOKIlokiQKCqkcTTPIVXpivxSEROserometer	stateminedvpnxprtmovrergoabbcdivipuradfineon3docktruecsorai)METER	STATEMINEDVPNXPRTMOVRERGOABBCDIVIPURADFINEON3DOCKTRUECSORAIMARGIN_TRADEMARGIN_ISOLATED_TRADETRADE)r  r  r>   )r6   symbolSeparatorfetchMyTradesMethodr]   rp   r   versionspartneraccountsByTypenetworksmarginModes)commonCurrenciesoptions)deep_extendsuperr-   describer*   r$   r#   r   r!   r   r   r%   r&   r'   r   r"   r    r(   r   parse_number)self	__class__s    _/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/async_support/kucoin.pyr  zkucoin.describe$   s"   fd 3 3 < < > > PA
(PA
HPA
 $PA
 	PA

 tPA
 PA
 4PA
 ~PA
 PA
  TTT $T 	T
 %T %T $TT 'T "4T tT $UT  T 'T /T ,TT  0!T" t#T T$ %T& &t'T( ')T* (+T, "4-T. %d/T0 T1T2  3T4 5T6 &t7T8 +D9T: )$;T< $T=T> '?T@ (ATB "4CTD &tET T TF 1$GTH  ITJ *4KTL +DMTN &uOTP #EQTR *5STT $UUTV "5WTX *5YTZ +E[T\ #D]T^ t_T` %eaTb /cTd "5eTf +EgT T Th iTj !%kTl  mTn doTp $UqTr +EsTt "4uTv dwTx !$yTz "5{T| &t}T~ #DT@ $UATB )%CTD tETF tGTH IT TJ "##'$)'+"'$($('+$!&#(  gT T TPA
~ ~P67&F%E#<=  0- PA
^ " $ $_PA
h $c 0 "1	
 21 ,T ' "3 @ 5a 6q +C )# !# $S  !#!$ 6q%& ('. (- 8G#RG #CG /	G
 +AG .qG 4QG .qG #BG 3DG 'G &rG )"G *2G  ,R!G" ,S#G$ #C%G& ('G G( &r)G* +B+G, -b-G. 0/G0 (1G2 #A3G4 %a5G8 89G: 21;G< 21=G> +A?G@ 3AAGB )!CGD .qEGF =aGGH :1IGJ #AKG G GL !!MGN 'OGP +AQGR 9!SGT  UGV &rWGX %aYGZ /[G\ ;A]G^ .q_G` 6qaGb 7cGd %aeGh 21iGj 0kGl 5amGn DQoG Gp ,-$&-//1,.57)+(*+-(*69)++-67MG G GP&*D& &r& -b	& ,R& &s& 6q& 0& 22& '& &r& $Q& )!&  )!!&" *1#&$ /%&& *1'&( 4Q)&* #$'(()&'%&+,01()-.)+(*$&"$02*,K& & &N%r 5b	 .q 3A =a B1 5a $Q .r +A 9! !"  /!" <Q#$ ,Q%& .q'( 7)* '(67EF,.3  aK KZ*C,c !! *3	
 )# *2 ( &s )# &q 6s ( +C 8 1#  $Q!" !!#& /' . (-" "8-q +C	
 / ( !! %a +C +C -c   &s .r  #A!" $Q#$ 3B%& 8'( *3)0 )+')"#'((+?@13:;<=*,   -0;>"$&*	 M,# ,#\ 6  +,-.4556	  /0-.45;<	  3A uK KiPA
@  APA
` YaPA
b s%}s&s &}s =l	s
 @s N}s OPas 7
s :s .s <s <s <s <s ,s  /!s" /#s s$ .%s& l's( j)s* m+s, m-s. m/s0 /1s2 l3s4 m5s6 m7s8 .9s: m;s< /=s> j?s@ /AsB .CsD lEs s sF lGsH lIsJ lKsL lMsN lOsP lQsR mSsT lUsV lWsX lYsZ l[s\ l]s^ m_s` lasb mcsd lesf mgs s sh .isj mksl mmsn mosp mqsr msst /usv mwsx lysz l{s| l}s~ ls@ lAsB lCsD lEsF lGsH lIs s sJ mKsL mMsN mOsP mQsR mSsT mUsV lWsX lYsZ l[s\ .]s^ ._s` masb mcsd /esf lgsh /isj /ks s sl nmsn /osp lqsr isst 1usv lwsx 1ysz 1{s| 1}s~ 1s@ 1AsB lCsD /EsF lGsH lIsJ lKsL jMs sN 2*'*((.(.2,(es s sj 6G/? ky ycPA
V !%"&!..w77!..w77 "..s33T5F5Fw5O5OP!..t44d6G6G6P6PQ!..u55t7H7H7R7RS!..u55t7H7H7R7RS!..v668I8I(8S8ST!..v668I8I(8S8ST!..v668I8I(8S8ST!..v668I8I(8S8ST!..w779J9J99U9UV!..w779J9J89T9TU!..w779J9J99U9UV!..w779J9J89T9TU!..w779J9J99U9UV"  "..s33T5F5Fw5O5OP!..t44d6G6G6Q6QR!..u55t7H7H7R7RS!..u55t7H7H7R7RS!..v668I8I(8S8ST!..v668I8I#8N8NO!..v668I8I#8N8NO!..v668I8I#8N8NO!..w779J9J:9V9VW!..w779J9J:9V9VW!..w779J9J:9V9VW!..w779J9J:9V9VW!..w779J9J:9V9VW"! % %N "'"' "!	 O- -WPA
t  ! !  #&':$(%&)-$ $ '! !% *.59'+	   " '"  8"  '	" 
 +D"  .t"  0"  0"  6t"  6t"  <T"  24"   :4!" " ;D#" $ )$%" ( 6t)" * 4T+" , 9$-" . JN/3(,15-1,0/3,0:>-1/3C"  "  " J 15;?597;,0)-/348-1,0(,&*48#! !. ;?IM0437<@*.# #oC  C J *D!'[R Rl %E 
 ,E   $&% *"%(&$$# #N5N%xN UN U	N
 VN WN 5N 5N FN 5N UN EN jN VN WN  F!N" 5#N N$ 5%N& 
'N( 5)N* F+N, F-N. F/N0 51N2 53N4 F5N6 77N8 F9N: 5;N< 5=N> 7?N@ HANB FCND FEN N NF 5GNH 5INJ FKNL 5MNN 5ONP FQNR 5SNT FUNV 5WNX 5YNZ 6[N\ W]N^ 5_N` VaNb FcNd 5eNf 5gN N Nh WiNj 5kNl WmNn FoNp FqNr 5sNt 5uNv FwNx FyNz 5{N| 5}N~ 5N@ FANB 5CND FENF 5GNH 5IN N NJ FKNL FMNN FONP FQNR 5SNT $UNV 5WNX FYNZ 5[N\ 5]N^ F_N` 5aNb FcNd FeNf WgNh 5iNj FkN N Nl UmNn WoNp 5qNr 5sNt 5uNv FwNx 5yNz 5{N| 5}N~ 5N@ 5ANB 5CND 5ENF 5GNH 5INJ WKNL 5MN N NN eONP 5QNR FSNT 5UNV 5WNX 5YNZ W[N^ F_N` 5aNb hcNf FgNh FiNj FkNl 5mNn $oNp FqNr FsN Nt %!,""""""" $"""SN N N` , 7#   Y
Q Q}PA
 PA
 PA
 P P P	    c                 *    |                                  S N)milliseconds)r  s    r  noncezkucoin.nonce  s      """r  c                 h   K   |                      |           d{V }|                     |d          S )aE  
        fetches the current integer timestamp in milliseconds from the exchange server
        :see: https://docs.kucoin.com/#server-time
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        Ndata)publicGetTimestampsafe_integer)r  paramsresponses      r  
fetch_timezkucoin.fetch_time  sE       0088888888   6222r  c                    K   |                      |           d{V }|                     |di           }|                     |d          }|dk    rdndddd|dS )aE  
        the latest known information on the availability of the exchange API
        :see: https://docs.kucoin.com/#service-status
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `status structure <https://docs.ccxt.com/#/?id=exchange-status-structure>`
        Nr  r   openokmaintenance)r   updatedetaurlinfo)publicGetStatus	safe_dictsafe_string)r  r  r  r  r   s        r  fetch_statuszkucoin.fetch_status  s       --f55555555 ~~h33!!$11%//ddm
 
 	
r  returnc                 8  K   |                      |           d{V }|                     |d          }|                     | j        di           }|                     |dd          }i }|r|                     |           d{V }|                     |di           }|                     |dg           }|                     |d          }	g }
t          dt          |                    D ]/}||         }| 	                    |d          }|
                    d	          \  }}|                     |          }|                     |          }|                     |	|i           }| 	                    |d
          }| 	                    |d          }| 	                    |d          }| 	                    |d          }|
                    i d|d|dz   |z   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|                     t          j        ||                    |                     t          j        ||                    ddddd|                     |d"          |                     |d#          d$ddd%|                     |d&          |                     |d'          d%ddd%|                     |d(          |                     |d)          d%d*d|d+           1|
S ),aO  
        retrieves data on all markets for kucoin
        :see: https://docs.kucoin.com/#get-symbols-list-deprecated
        :see: https://docs.kucoin.com/#get-all-tickers
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        Nr  rp   r  Tr   symbolr   r  makerFeeRatetakerFeeRatemakerCoefficienttakerCoefficientr/   /basequotesettlebaseIdquoteIdsettleIdtyper>   r?   isMarginEnabledr@   FrA   rB   activeenableTradingr  linearbaseIncrementpriceIncrement)amountpriceminmaxbaseMinSizebaseMaxSizequoteMinSizequoteMaxSize)leverager  r  cost)inverser  r  contractSizeexpiryexpiryDatetimestrike
optionType	precisionlimitscreatedr  )publicGetSymbols	safe_listr  r  	safe_boolpublicGetMarketAllTickersindex_byrangelenr  splitsafe_currency_codeappendr  r+   
string_mulsafe_number)r  r  r  r  r  r  tickersResponsetickersDatatickerstickersByMarketIdresultimarketr/   r  r  r  r  r   r  r  r  r  s                          r  fetch_marketszkucoin.fetch_markets  s      ..v666666664 ~~h//..~rBB>>'3EtLL 	K$($B$B6$J$JJJJJJJO: nn_fbAA..h;; MM'8<<q#d))$$ >	 >	A!WF!!&(33B hhsmmOFG**622D++G44E^^$5r2>>F++FNCCL++FNCCL#//8JKK#//8JKKMM 2b2$*u,2 2 	2
 $2 &2 72 D2 2 2 $..1BCC2 2 %2 %2 $..AA2  E!2" $#2$  **7+=lL\+]+]^^**7+=lL\+]+]^^ $"&""..vGG!--f6FGG   $#! !
  $//FF#//FF 
  $# 
  $//GG#//GG  $  c2 2 2 2 2 2 2f r  c                   K   g }|                     |                     |                     |                     |                     ddd                     t          j        |  d{V }|                     |di           }|                     |dg           }|                     |di           }|                     |dg           }|                     |d          }i }	t          dt          |                    D ]T}
||
         }| 
                    |d          }| 
                    |d	          }|                     |          }d}d}i }|                     |d
g           }|                     |                     ||g           d          }| 
                    |d          }|                     |                     |                    }t          |          }|sd}d}t          d|          D ]2}||         }| 
                    |d          }|                     |          }|                     |dd          }||}n|p|}|                     |dd          }||}n|p|}|                     ||i           }||| 
                    |d          ||o||                     |d          |||                     |                     | 
                    |d                              |                     |d          dd|                     |d          dddd
||<   4|dk    o|dk    }||||rdnd|||p|||d| j        |d|	|<   V|	S )a	  
        fetches all available currencies on an exchange
        :see: https://docs.kucoin.com/#get-currencies
        :param dict params: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        r]   'webExchangeGetCurrencyCurrencyChainInfoTNr   r  r   currencyfullNamechainschainr  FchainIdisWithdrawEnabledisDepositEnabled	chainNamewithdrawalMinFeewalletPrecisionwithdrawalMinSizer  depositMinSizer   r  )
r  r/   r0   coder  feer  r   r  r  2fiatcrypto)r/   r0   r)  r  r  r  r  r  r   r*  r  r  )r  publicGetCurrenciesfetch_web_endpointasynciogatherr  r  group_byr  r  r  r  r
  r  parse_precisionnetwork_id_to_coder  r  r  )r  r  promises	responsescurrenciesResponsecurrenciesDataadditionalResponseadditionalDataadditionalDataGroupedr  r  entryr/   r0   r)  r!  r"  r  r  extraChainsDatarawPrecisionr  chainsLengthjr  r   networkCodechainWithdrawEnabledchainDepositEnabledchainExtraDataisFiats                                  r  fetch_currencieszkucoin.fetch_currencieso  s      0088999> 	//0AClnrsstttF ".(3333333	!^^Iq"==(:FBGG!^^Iq"==(:FBGG $nj I Iq#n--.. D	 D	A"1%E!!%44B##E:66D**2..D $#H^^E8R88F"mmDNN;PRTVX,Y,Y[bccO++E;??L))$*>*>|*L*LMMIv;;L )$)!#( 1l++ # #q	**5)<<"55g>>'+~~e=PRW'X'X$$,(<%%(9(Q=Q%&*nnU<NPU&V&V##+':$$'7'N;N$!%"!M!M!! ,,UK@@'2J7J++E3EFF2 4!%!2!243G3GHXHXYgizH{H{3|3|!}!} $(#3#3E;N#O#O#'% %
 $(#3#3NDT#U#U#'$ $	 	) )%%, #c)B0AF"(6h&+@/@+-+$ F4LL r  c           	        K   |                      |           d{V }|                     |dg           }g }t          dt          |                    D ]|}||         }|                     |d          }|                     |d          }|                     |          }	|                     |d          }
|                    ||
|	|	|d           }|S )aT  
        fetch all the accounts associated with a profile
        :see: https://docs.kucoin.com/#list-accounts
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `account structures <https://docs.ccxt.com/#/?id=account-structure>` indexed by the account type
        Nr  r   r/   r  r  )r/   r  r  r)  r  )privateGetAccountsr  r  r  r  r  r  )r  r  r  r  r  r  account	accountId
currencyIdr)  r  s              r  fetch_accountszkucoin.fetch_accounts  s       00888888880 ~~h33q#d))$$ 	 	A1gG(($77I))':>>J**:66D##GV44DMM       r  r)  c                   K   |                                   d{V  |                     |          }d|d         i}d}|                     |          \  }}|*|                     |                                          |d<   |                     |                     ||                     d{V }|                     |di           }i }|                     |d          ||<   ||i dS )a]  
        *DEPRECATED* please use fetchDepositWithdrawFee instead
        :see: https://docs.kucoin.com/#get-withdrawal-quotas
        :param str code: unified currency code
        :param dict params: extra parameters specific to the exchange API endpoint
        :returns dict: a `fee structure <https://docs.ccxt.com/#/?id=fee-structure>`
        Nr  r/   r  r  withdrawMinFee)r  r   r  )	load_marketsr  handle_network_code_and_paramsnetwork_code_to_idlowerprivateGetWithdrawalsQuotasextendr  r  )	r  r)  r  r  requestrA  r  r  withdrawFeess	            r  fetch_transaction_feezkucoin.fetch_transaction_fee7  s      !!!!!!!!!==&&
 "AA&IIV"#66{CCIIKKGG99$++gv:V:VWWWWWWWW~~h33!--d4DEET$
 
 	
r  c                   K   |                                   d{V  |                     |          }d|d         i}d}|                     |          \  }}|*|                     |                                          |d<   |                     |                     ||                     d{V }|                     |d          }|                     ||          S )aH  
        fetch the fee for deposits and withdrawals
        :see: https://docs.kucoin.com/#get-withdrawal-quotas
        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.network]: The chain of currency. This only apply for multi-chain currency, and there is no need for single chain currency; you can query the chain through the response of the GET /api/v2/currencies/{currency} interface
        :returns dict: a `fee structure <https://docs.ccxt.com/#/?id=fee-structure>`
        Nr  r/   r  r  )	rO  r  rP  rQ  rR  rS  rT  r  parse_deposit_withdraw_feer  r)  r  r  rU  rA  r  r  s           r  fetch_deposit_withdraw_feez!kucoin.fetch_deposit_withdraw_feeR  s       !!!!!!!!!==&&
 "AA&IIV"#66{CCIIKKGG99$++gv:V:VWWWWWWWW& ~~h//..tX>>>r  Nr  c                 X   |d d dd d di d}|                      |d          }|r|                     |dd          |d         d<   d|d         d	<   |                     |d
          }|rA|                     ||                     |d                    }|d         d d dd|d         |<   |S )N)r*  r  )r  r   r  r  r!  r$  rN  r   r*  Fr  r  r)  r(  r  )r  safe_number_2r  r4  )r  r*  r  r  r!  	networkIdrA  s          r  rY  z!kucoin.parse_deposit_withdraw_feez  s   " " 
 "  
 
 !NN30CDD 	(,(:(:3@RTd(e(eF:u%/4F:|,((g66I "55iAQAQRZ\bAcAcdd &z 2#&*   3 3z";/ r  c                    |                      | j        |dd          }|                     |d|          }|                     | j        d          }|                     ||          }|Nt	          |                                          }t          | j        dz   d                    |          z             | 	                    |d          }|dk    p|dk    p|d	k    S )
NdefaultTyper  r  r  z' isFuturesMethod() type must be one of z, r  rA   futures)
safe_string_2r  r  r  listkeysr   r/   joinomit)r  
methodNamer  r`  requestedTyper  r  rd  s           r  is_futures_methodzkucoin.is_futures_method  s     ((z=RYZZ((EE6FGG>><++--..D*S SVZV_V_`dVeVe efff66**z!Otx'7OTY=NOr  r  c           	         |                      |d          }|t          j        |d          }|                     |dd          }|                      |d|          }|                      |d          }|                     ||d          }|d         }|                      |d          }|                      |d	          }|                     |d
d          }	|                     i d|d|	d|                     |	          d|                      |d          d|                      |d          d|                     |dd          d|                      |d          d|                     |dd          d|                      |d          dd d|                      |d          d|d|dd d|                      |d          d|d |                      |d!          |||d"|          S )#N
changeRate100lastlastTradedPricer  r  r  volvolValuetimedatetimer   highlowbidbuybestBid	bidVolumebestBidSizeasksellbestAsk	askVolumebestAskSizevwapr  closepreviousClosechangechangePricer  averageaveragePrice)
baseVolumequoteVolumer  )r  r+   r  rb  safe_marketsafe_integer_2safe_tickeriso8601)
r  r   r  r  rm  marketIdr  r  r  r   s
             r  parse_tickerzkucoin.parse_ticker  s|   p %%fl;;
! +J>>J!!&&2CDD66##FH55!!(FC88!%%fe44
&&vz::''
CC	 !
f!
!
 Y//!
 D$$VV44	!

 4##FE22!
 4%%feY??!
 ))&-@@!
 4%%ffi@@!
 ))&-@@!
 D!
 D$$VV44!
 T!
 D!
 T!
 d&&v}==!
  *!!
" t''??#!
$ %&)!
 !
 !
* +  	r  r   c                   K   |                                   d{V  |                     |          }|                     |           d{V }|                     |di           }|                     |dg           }|                     |d          }i }t          dt          |                    D ]E}|||         d<   |                     ||                   }	| 	                    |	d          }
|
|	||
<   F| 
                    |d|          S )a  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
        :see: https://docs.kucoin.com/#get-all-tickers
        :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        Nr  r   rq  r   r  )rO  market_symbolsr	  r  r  r  r  r  r  r  filter_by_array_tickers)r  r   r  r  r  r  rq  r  r  r   r  s              r  fetch_tickerszkucoin.fetch_tickers  s+      !!!!!!!!!%%g..77????????: ~~h33..x44  v..q#g,,'' 	( 	(A!%GAJv&&wqz22F%%fh77F!!'v++FHgFFFr  r  c                   K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |d         |          S )a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :see: https://docs.kucoin.com/#get-24hr-stats
        :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/   r  )rO  r  publicGetMarketStatsrT  r  )r  r  r  r  rU  r  s         r  fetch_tickerzkucoin.fetch_tickerD  s       !!!!!!!!!V$$fTl
 224;;w3O3OPPPPPPPP0   &!16:::r  c           	         |                      |d          |                     |d          |                     |d          |                     |d          |                     |d          |                     |d          gS )Nr   r   r   r   r   r   )safe_timestampr  )r  ohlcvr  s      r  parse_ohlcvzkucoin.parse_ohlcvk  s     q))UA&&UA&&UA&&UA&&UA&&
 	
r  r   sincelimitc           	      *  K   |                                   d{V  d}|                     |dd          \  }}|r!|                     d|||||d           d{V S |                     |          }|d         }||                     | j        ||          d}	|                     |          dz  }
|                                 }|r|                     t          t          j        |dz                                |	d	<   ||                     | j        d
d          }|                     |||
z            }nD|B|||
z  z
  }|                     t          t          j        |dz                                |	d	<   |                     t          t          j        |dz                                |	d<   |                     |                     |	|                     d{V }|                     |dg           }|                     |||||          S )au  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :see: https://docs.kucoin.com/#get-klines
        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        NFrs   paginatei  r/   )r  r    startAtfetchOHLCVLimitendAtr  )rO  handle_option_and_params"fetch_paginated_call_deterministicr  r  r   parse_timeframer  parse_to_intintmathfloorr  r  sumpublicGetMarketCandlesrT  r  parse_ohlcvs)r  r  	timeframer  r  r  r  r  r  rU  durationr  r  r  s                 r  fetch_ohlcvzkucoin.fetch_ohlcv  s>      !!!!!!!!!88zZZ& 	~@@vW\^cenpvx|}}}}}}}}}V$$$<$$T_iKK
 
 ''	22T9!!##!%!2!23tz%$,7O7O3P3P!Q!QGI}
 ))$,8I4PPHHUEH$455EEEH,,E!%!2!23tz%$,7O7O3P3P!Q!QGI,,SEDL1I1I-J-JKK44T[[&5Q5QRRRRRRRR ~~h33  vy%GGGr  c                   K   |                                   d{V  |                     |          }d|d         i}d}|                     |          \  }}|*|                     |                                          |d<   |                     |                     ||                     d{V }|                     |di           }|                     ||          S )a  
        :see: https://docs.kucoin.com/#create-deposit-address
        create a currency deposit address
        :param str code: unified currency code of the currency for the deposit address
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.network]: the blockchain network name
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        Nr  r/   r  r  )	rO  r  rP  rQ  rR  privatePostDepositAddressesrT  r  parse_deposit_addressrZ  s           r  create_deposit_addresszkucoin.create_deposit_address  s       !!!!!!!!!==&&
 "AA&IIV"#66{CCIIKKGG99$++gv:V:VWWWWWWWW ~~h33))$999r  c                   K   |                                   d{V  |                     |          }d|d         i}d}|                     |          \  }}|*|                     |                                          |d<   | j        d         d         d         d         }d	| j        d         d         d         d<   |                     |                     ||                     d{V }|| j        d         d         d         d<   |                     |d
          }|t          | j
        dz             |                     ||          S )a  
        fetch the deposit address for a currency associated with self account
        :see: https://docs.kucoin.com/#get-deposit-addresses-v2
        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.network]: the blockchain network name
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        Nr  r/   r  r  r   r  r   r  r  zr fetchDepositAddress() returned an empty response, you might try to run createDepositAddress() first and try again)rO  r  rP  rQ  rR  r  privateGetDepositAddressesrT  
safe_valuer   r/   r  )	r  r)  r  r  rU  rA  r6   r  r  s	            r  fetch_deposit_addresszkucoin.fetch_deposit_address  st      !!!!!!!!!==&&
 "AA&IIV"#66{CCIIKKGG,z*95e<=PQJNZ +E23FG88Wf9U9UVVVVVVVV KRZ +E23FGx00<  +_  !_  `  `  `))$999r  c           
      2   |                      |d          }||                    dd          }d }|#|d         }|dk    r|                     |           ||||                      |d          |                     |                      |d                    dS )	Naddresszbitcoincash: r/   NIMmemor  )r  r  r  tagnetwork)r  replacecheck_addressr4  )r  depositAddressr  r  r)  s        r  r  zkucoin.parse_deposit_address  s    "">9==oonb99GD>Du}}""7+++"##NF;;..t/?/?PW/X/XYY
 
 	
r  c                 ,  K   |                                   d{V  |                     |          }d|d         i}| j        d         d         d         d         }d| j        d         d         d         d<   |                     |                     ||                     d{V }|| j        d         d         d         d<   |                     |d	g           }|                     ||d
         gdd|d         i          }|                     |d          S )a  
        :see: https://docs.kucoin.com/#get-deposit-addresses-v2
        fetch the deposit address for a currency associated with self account
        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an array of `address structures <https://docs.ccxt.com/#/?id=address-structure>`
        Nr  r/   r  r   r  r   r7   r  r)  Fr  )rO  r  r  r  rT  r  parse_deposit_addressesr
  )	r  r)  r  r  rU  r6   r  r  parseds	            r  "fetch_deposit_addresses_by_networkz)kucoin.fetch_deposit_addresses_by_network   s7      !!!!!!!!!==&&
 ,z*95e<=PQJNZ +E23FG88Wf9U9UVVVVVVVV  KRZ +E23FG&"55--fx7G6H%R
   }}VY///r  c           
        K   |                                   d{V  |                     |          }|                     |dd          }d|d         i}|                     d          }d}|r|o|dk    r9||d<   |)|dk    s|dk    r||d	<   nt	          | j        d
z             |r|nd|d	<   |                     |                     ||                     d{V }n/|                     |                     ||                     d{V }| 	                    |di           }	|                     |	d          }
| 
                    |	|d         |
dd|dz
  |dz
            }|                     |	d          |d<   |S )a  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :see: https://www.kucoin.com/docs/rest/spot-trading/market-data/get-part-order-book-aggregated-
        :see: https://www.kucoin.com/docs/rest/spot-trading/market-data/get-full-order-book-aggregated-
        :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levelr   r  r/   Fr   d   r  z2 fetchOrderBook() limit argument must be 20 or 100r  rq  bidsasksr   sequencer  )rO  r  r  check_required_credentialsr   r/   'publicGetMarketOrderbookLevelLevelLimitrT  privateGetMarketOrderbookLevel2r  parse_order_book)r  r  r  r  r  r  rU  isAuthenticatedr  r  r   	orderbooks               r  fetch_order_bookzkucoin.fetch_order_book&  s      !!!!!!!!!V$$!!&'155VD\*99%@@ 	`%"3zz#( $#+0((+DG6j,jkkk,1#:55s !II$++V]_eJfJfggggggggHH!AA$++gW]B^B^________H@ ~~h33%%dF33	))$x0@)VU[]bef]fhmpqhqrr	!..tZ@@	'r  c                     |                      |dd          }|                     |d          }|                     |d          }|d u}|d u}|r|s|r|s|r|rt          | j        dz             |||gS )NtriggerPrice	stopPricestopLossPricetakeProfitPricezW createOrder() - you should use either triggerPrice or stopLossPrice or takeProfitPrice)safe_value_2r  r   r/   )r  r  r  r  r  
isStopLossisTakeProfits          r  handle_trigger_priceszkucoin.handle_trigger_pricesg  s    ((MM@@//&2CDD"$.
&d2 	E< 	E\ 	Em 	EQ] 	Ebn 	E  +D  !D  E  E  Em_==r  r  sider  r  c                   K   |                                   d{V  |                     |          }|                     |dd          }|                     |d          }|                     |dd          }	|                     |          \  }
}}|                     |d          }|
p|p|}|                     d|          }|                     |d          }|dk    p|du}|                     ||||||          }d}|r:|r|                     |           d{V }n| 	                    |           d{V }nu|	r| 
                    |           d{V }nW|r|                     |           d{V }n9|r|                     |           d{V }n|                     |           d{V }|                     |d	i           }|                     ||          S )
a  
        Create an order on the exchange
        :see: https://docs.kucoin.com/spot#place-a-new-order
        :see: https://docs.kucoin.com/spot#place-a-new-order-2
        :see: https://docs.kucoin.com/spot#place-a-margin-order
        :see: https://docs.kucoin.com/spot-hf/#place-hf-order
        :see: https://www.kucoin.com/docs/rest/spot-trading/orders/place-order-test
        :see: https://www.kucoin.com/docs/rest/margin-trading/orders/place-margin-order-test
        :param str symbol: Unified CCXT market symbol
        :param str type: 'limit' or 'market'
        :param str side: 'buy' or 'sell'
        :param float amount: the amount of currency to trade
        :param float [price]: *ignored in "market" orders* the price at which the order is to be fullfilled at in units of the quote currency
        :param dict [params]:  extra parameters specific to the exchange API endpoint
        :param float [params.triggerPrice]: The price at which a trigger order is triggered at
        :param str [params.marginMode]: 'cross',  # cross(cross mode) and isolated(isolated mode), set to cross by default, the isolated mode will be released soon, stay tuned
        :param str [params.timeInForce]: GTC, GTT, IOC, or FOK, default is GTC, limit orders only
        :param str [params.postOnly]: Post only flag, invalid when timeInForce is IOC or FOK
         *
         * EXCHANGE SPECIFIC PARAMETERS
        :param str [params.clientOid]: client order id, defaults to uuid if not passed
        :param str [params.remark]: remark for the order, length cannot exceed 100 utf8 characters
        :param str [params.tradeType]: 'TRADE',  # TRADE, MARGIN_TRADE  # not used with margin orders
         * limit orders ---------------------------------------------------
        :param float [params.cancelAfter]: long,  # cancel after n seconds, requires timeInForce to be GTT
        :param bool [params.hidden]: False,  # Order will not be displayed in the order book
        :param bool [params.iceberg]: False,  # Only a portion of the order is displayed in the order book
        :param str [params.visibleSize]: self.amount_to_precision(symbol, visibleSize),  # The maximum visible size of an iceberg order
         * market orders --------------------------------------------------
        :param str [params.funds]:  # Amount of quote currency to use
         * stop orders ----------------------------------------------------
        :param str [params.stop]:  Either loss or entry, the default is loss. Requires stopPrice to be defined
         * margin orders --------------------------------------------------
        :param float [params.leverage]: Leverage size of the order
        :param str [params.stp]: '',  # self trade prevention, CN, CO, CB or DC
        :param bool [params.autoBorrow]: False,  # The system will first borrow you funds at the optimal interest rate and then place an order for you
        :param bool [params.hf]: False,  # True for hf order
        :param bool [params.test]: set to True to test an order, no order will be created but the request will be validated
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        NtestFr  	tradeTyperM   r   r  r  )rO  r  r  rf  r  r  handle_margin_mode_and_paramscreate_order_requestprivatePostMarginOrderTestprivatePostOrdersTestprivatePostHfOrdersprivatePostStopOrderprivatePostMarginOrderprivatePostOrdersr  parse_order)r  r  r  r  r  r  r  r  	testOrderisHfr  r  r  r  isTriggerOrdermarginResult
marginModeisMarginOrderorderRequestr  r  s                        r  create_orderzkucoin.create_orderq  s]     R !!!!!!!!!V$$NN66599	66**~~fdE227;7Q7QRX7Y7Y4m_$$V[99	&J-J?99-PP%%lA66
!^3Mz7M00tVUTZ[[ 	B J!%!@!@!N!NNNNNNN!%!;!;L!I!IIIIIII 	B!55lCCCCCCCCHH 	B!66|DDDDDDDDHH 	B!88FFFFFFFFHH!33LAAAAAAAAH ~~h33f---r  r  c                    K   |                                   d{V  ||d<   |                     |d||d|           d{V S )a  
        create a market order by providing the symbol, side and cost
        :see: https://www.kucoin.com/docs/rest/spot-trading/orders/place-order
        :param str symbol: unified symbol of the market to create an order in
        :param str side: 'buy' or 'sell'
        :param float cost: how much you want to trade in units of the quote currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  r  )rO  r  )r  r  r  r  r  s        r  create_market_order_with_costz$kucoin.create_market_order_with_cost  se       !!!!!!!!!v&&vxtT6RRRRRRRRRr  c                 v   K   |                                   d{V  |                     |d||           d{V S )a  
        create a market buy order by providing the symbol and cost
        :see: https://www.kucoin.com/docs/rest/spot-trading/orders/place-order
        :param str symbol: unified symbol of the market to create an order in
        :param float cost: how much you want to trade in units of the quote currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nrv  rO  r  r  r  r  r  s       r  !create_market_buy_order_with_costz(kucoin.create_market_buy_order_with_cost  sX       !!!!!!!!!77tVTTTTTTTTTr  c                 v   K   |                                   d{V  |                     |d||           d{V S )a  
        create a market sell order by providing the symbol and cost
        :see: https://www.kucoin.com/docs/rest/spot-trading/orders/place-order
        :param str symbol: unified symbol of the market to create an order in
        :param float cost: how much you want to trade in units of the quote currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr{  r  r  s       r  "create_market_sell_order_with_costz)kucoin.create_market_sell_order_with_cost  sX       !!!!!!!!!77fUUUUUUUUUr  r   c           	      ^  K   |                                   d{V  g }d}t          dt          |                    D ]}||         }|                     |d          }||}n||k    rt	          | j        dz             |                     |d          }|dk    rt	          | j        dz             |                     |d          }	|                     |d	          }
|                     |d
          }|                     |di           }|                     |||	|
||          }|                    |           | 	                    |          }|d         |d}| 
                    |dd          }|                     |d          }d}|r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |di           }|                     |dg           }|                     |          S )a  
        create a list of trade orders
        :see: https://www.kucoin.com/docs/rest/spot-trading/orders/place-multiple-orders
        :see: https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/place-multiple-hf-orders
        :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
        :param dict [params]:  extra parameters specific to the exchange API endpoint
        :param bool [params.hf]: False,  # True for hf orders
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr   r  z; createOrders() requires all orders to have the same symbolr  r  z* createOrders() only supports limit ordersr  r  r  r  r/   )r  	orderListr  Fr  )rO  r  r  r  r   r/   r  r  r  r  r  rf  privatePostHfOrdersMultirT  privatePostOrdersMultir  r  parse_orders)r  r   r  ordersRequestsr  r  rawOrderr  r  r  r  r  orderParamsr  r  rU  r  r  r  s                      r  create_orderszkucoin.create_orders  sb      !!!!!!!!!q#f++&& 	0 	0AayH''(;;H~!X%%$TW/l%lmmm##Hf55Dw +W!WXXX##Hf55D__Xx88FOOHg66E//(HbAAK44XtT6SXZeffL!!,////V$$Tl'
 
 ^^FD%0064(( 	W!::4;;wPV;W;WXXXXXXXXHH!88Wf9U9UVVVVVVVVH> ~~h33~~dFB//  &&&r  c                 .   |                      |          }|                     |t          |d         d         | j        | j                  }|dk    rEt          | j        dz   |d         z   dz   |                     |d         d                   z             |S )	Nr  quoteIncrementrw  z amount of r  z2 must be greater than minimum amount precision of r  r  )r  decimal_to_precisionr)   r  paddingModer#   r/   number_to_string)r  r  r  r  r  s        r   market_order_amount_to_precisionz'kucoin.market_order_amount_to_precision2  s    V$$**68VF^L\=]_c_qsw  tD  E  ES==tw69II  MA   A  DH  DY  DY  Z`  al  Zm  nv  Zw  Dx  Dx   x  y  y  yr  c                    |                      |          }|                     |dd|                                           }|                     |ddg          }|||d         |d}	|                     |dd          }
d }d }d }|                     d|          \  }}|dk    rf|
4|                     |ddg          }|                     ||
          }||	d<   nd|                     ||          }|                     ||          |	d	<   n4|                     ||          }||	d	<   |                     ||          |	d
<   | 	                    |d          }| 
                    |          \  }}}|p|p|}|dk    p|d u}|                     |g d          }|r|r|                     ||          |	d<   nS|s|rO|r'|dk    rdnd|	d<   |                     ||          |	d<   n&|dk    rdnd|	d<   |                     ||          |	d<   |dk    rt          | j        dz             |dk    r| j        d         |         |	d<   n|r|dk    rd|	d<   d }|                     |dk    d|          \  }}|rd|	d<   |                     |	|          S )N	clientOidclientOrderIdr/   )r  r  r  r  r  fundsrM   r  sizer  r  r  )r  r  r  r  r  rv  r<  lossstopr  z= createOrder does not support isolated margin for stop ordersr  r  marginModelFTpostOnly)r  rb  uuidrf  r]  r  r  amount_to_precisionprice_to_precisionr  r  r   r/   r  handle_post_onlyrT  )r  r  r  r  r  r  r  r  r  rU  quoteAmountamountString
costStringr  r  r  r  r  r  r  r  s                        r  r  zkucoin.create_order_request9  s$   V$$**6;QUQZQZQ\Q\]]6K#ABB&Tl	
 
 ((AA

!??vVV
F8&6FG+<==!BB6;WW
#-  #77GG"&":":66"J"J33FFCCL*GFO#66vuEEGG$$V[99	7;7Q7QRX7Y7Y4m_&J-J?!^3Mz7M6#d#d#dee 	4 \'+'>'>v|'T'T$$ \/ \  \26%--ggfGFO+/+B+B6=+Y+YGK((15ffWGFO+/+B+B6?+[+[GK(Z'' +j!jkkkw&&'+|M'B:'N$ 	4Z'')3&001A5&QQ& 	'"&GJ{{7F+++r  r/   c                   K   |                                   d{V  |                     |          }d|d         i}	|                     |dd          }
|
|
|	d<   n||	d<   ||                     ||          |	d<   ||                     ||          |	d<   |                     |                     |	|                     d{V }|                     |d	i           }|                     ||          S )
aA  
        edit an order, kucoin currently only supports the modification of HF orders
        :see: https://docs.kucoin.com/spot-hf/#modify-order
        :param str id: order id
        :param str symbol: unified symbol of the market to create an order in
        :param str type: not used
        :param str side: not used
        :param float amount: how much of the currency you want to trade in units of the base currency
        :param float [price]: the price at which the order is to be fullfilled, in units of the base currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.clientOrderId]: client order id, defaults to id if not passed
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  r/   r  r  orderIdnewSizenewPricer  )	rO  r  rb  r  r  privatePostHfOrdersAlterrT  r  r  )r  r/   r  r  r  r  r  r  r  rU  r  r  r  s                r  
edit_orderzkucoin.edit_orderr  s#      !!!!!!!!!V$$fTl
 **6;PP$#0GK  !#GI!%!9!9&&!I!IGI"&"9"9&%"H"HGJ66t{{7F7S7STTTTTTTT ~~h33f---r  c                   K   |                                   d{V  i }|                     |dd          }|                     |ddd          }|                     |dd          }|r9|t	          | j        dz             |                     |          }|d	         |d
<   d}	|                     |g d          }|||d<   |r0|                     | 	                    ||                     d{V }	n|r0| 
                    | 	                    ||                     d{V }	n|                     | 	                    ||                     d{V }	n||d<   |r0|                     | 	                    ||                     d{V }	na|r0|                     | 	                    ||                     d{V }	n/|                     | 	                    ||                     d{V }	|	S )a:  
        cancels an open order
        :see: https://docs.kucoin.com/spot#cancel-an-order
        :see: https://docs.kucoin.com/spot#cancel-an-order-2
        :see: https://docs.kucoin.com/spot#cancel-single-order-by-clientoid
        :see: https://docs.kucoin.com/spot#cancel-single-order-by-clientoid-2
        :see: https://docs.kucoin.com/spot-hf/#cancel-orders-by-orderid
        :see: https://docs.kucoin.com/spot-hf/#cancel-order-by-clientoid
        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param bool [params.stop]: True if cancelling a stop order
        :param bool [params.hf]: False,  # True for hf order
        :returns: Response from the exchange
        Nr  r  r  triggerFr  z8 cancelOrder() requires a symbol parameter for hf ordersr/   r  )r  r  r  r  r  r  )rO  rb  safe_bool_2r  r   r/   r  rf  ,privateDeleteStopOrderCancelOrderByClientOidrT  )privateDeleteHfOrdersClientOrderClientOid&privateDeleteOrderClientOrderClientOidprivateDeleteStopOrderOrderIdprivateDeleteHfOrdersOrderIdprivateDeleteOrdersOrderId)
r  r/   r  r  rU  r  r  r  r  r  s
             r  cancel_orderzkucoin.cancel_order  sf       !!!!!!!!!**6;PP	5AA^^FD%00 	-~'2l(lmmm[[((F &tGH6#Z#Z#Z[[$#0GK  k!%!R!RSWS^S^_fhnSoSo!p!ppppppp k!%!O!OPTP[P[\cekPlPl!m!mmmmmmm!%!L!LT[[Y`bhMiMi!j!jjjjjjj!#GI _!%!C!CDKKPWY_D`D`!a!aaaaaaa _!%!B!B4;;wX^C_C_!`!```````!%!@!@WV\A]A]!^!^^^^^^^r  c                 0  K   |                                   d{V  i }|                     |dd          }|                     |dd          }|                     |ddg          }|                     d|          \  }}||                     |          |d<   |5| j        d         |         |d<   |d	k    r|rt          | j        d
z             d}|r0|                     | 	                    ||                     d{V }n|rb|0| 
                    | 	                    ||                     d{V }n_|                     | 	                    ||                     d{V }n/|                     | 	                    ||                     d{V }|S )ad  
        cancel all open orders
        :see: https://docs.kucoin.com/spot#cancel-all-orders
        :see: https://docs.kucoin.com/spot#cancel-orders
        :see: https://docs.kucoin.com/spot-hf/#cancel-all-hf-orders-by-symbol
        :param str symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param bool [params.stop]: *invalid for isolated margin* True if cancelling all stop orders
        :param str [params.marginMode]: 'cross' or 'isolated'
        :param str [params.orderIds]: *stop orders only* Comma seperated order IDs
        :param bool [params.stop]: True if cancelling a stop order
        :param bool [params.hf]: False,  # True for hf order
        :returns: Response from the exchange
        Nr  Fr  rE   r  r  r  r  zA cancelAllOrders does not support isolated margin for stop orders)rO  r  rf  r  	market_idr  r   r/   privateDeleteStopOrderCancelrT  privateDeleteHfOrdersCancelAllprivateDeleteHfOrdersprivateDeleteOrders)	r  r  r  rU  r  r  r  queryr  s	            r  cancel_all_orderszkucoin.cancel_all_orders  s      !!!!!!!!!~~ffe44^^FD%006FD>22 >>?PRXYY
E $v 6 6GH!#'<#>z#JGK Z''D' +n!nooo 	S!>>t{{7TY?Z?Z[[[[[[[[HH 	S~!%!D!DT[[QXZ_E`E`!a!aaaaaaa!%!;!;DKKQV<W<W!X!XXXXXXX!55dkk'56Q6QRRRRRRRRHr  c                   K   |                                   d{V  |                                }|                     |dd          }|                     |dd          }|                     |dd          }	|                     |g d          }|                     d|          \  }
}|d	k    rd
}n|dk    rd}d|i}d}| |                     |          }|d         |d<   |||d<   |||d<   |r||d<   |                     | j        d         |
d          |d<   d}|r0| 	                    | 
                    ||                     d{V }n|	rl|d
k    r0|                     | 
                    ||                     d{V }ne|dk    r/|                     | 
                    ||                     d{V }n/|                     | 
                    ||                     d{V }|                     |d          }||                     ||||          S |                     |di           }|                     |dg           }|                     ||||          S )a.  
        fetch a list of orders
        :see: https://docs.kucoin.com/spot#list-orders
        :see: https://docs.kucoin.com/spot#list-stop-orders
        :see: https://docs.kucoin.com/spot-hf/#obtain-list-of-active-hf-orders
        :see: https://docs.kucoin.com/spot-hf/#obtain-list-of-filled-hf-orders
        :param str status: *not used for stop orders* 'open' or 'closed'
        :param str symbol: unified market symbol
        :param int [since]: timestamp in ms of the earliest order
        :param int [limit]: max number of orders to return
        :param dict [params]: exchange specific params
        :param int [params.until]: end time in ms
        :param bool [params.stop]: True if fetching stop orders
        :param str [params.side]: buy or sell
        :param str [params.type]: limit, market, limit_stop or market_stop
        :param str [params.tradeType]: TRADE for spot trading, MARGIN_TRADE for Margin Trading
        :param int [params.currentPage]: *stop orders only* current page
        :param str [params.orderIds]: *stop orders only* comma seperated order ID list
        :param bool [params.stop]: True if fetching a stop order
        :param bool [params.hf]: False,  # True for hf order
        :returns: An `array of order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nuntiltillr  Fr  )r  r  r0  r/  rz   r  r  closeddoner   r/   r  r  pageSizer  r  r  r  r  items)rO  rR  r  r  rf  r  r  r  r  privateGetStopOrderrT  privateGetHfOrdersActiveprivateGetHfOrdersDoneprivateGetOrdersr  r  r  )r  r   r  r  r  r  lowercaseStatusr/  r  r  r  r,  rU  r  r  listDataresponseDatar   s                     r  fetch_orders_by_statuszkucoin.fetch_orders_by_status  s     . !!!!!!!!! ,,..##FGV<<~~ffe44^^FD%006#B#B#BCC >>?TV\]]
Ef$$&OO(($Oo
 [[((F &tGH!&GI"'GJ 	%$GG#//]0KZY`aa 	P!55dkk'56Q6QRRRRRRRRHH 	P(**!%!>!>t{{7TY?Z?Z![![[[[[[[ F**!%!<!<T[[RW=X=X!Y!YYYYYYY!224;;w3N3NOOOOOOOOHX >>(F33$$XvueDDD~~h;;gr::  >>>r  c                    K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S |                     d||||           d{V S )a~  
        fetches information on multiple closed orders made by the user
        :see: https://docs.kucoin.com/spot#list-orders
        :see: https://docs.kucoin.com/spot#list-stop-orders
        :see: https://docs.kucoin.com/spot-hf/#obtain-list-of-active-hf-orders
        :see: https://docs.kucoin.com/spot-hf/#obtain-list-of-filled-hf-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 int [params.till]: end time in ms
        :param str [params.side]: buy or sell
        :param str [params.type]: limit, market, limit_stop or market_stop
        :param str [params.tradeType]: TRADE for spot trading, MARGIN_TRADE for Margin Trading
        :param bool [params.stop]: True if fetching a stop order
        :param bool [params.hf]: False,  # True for hf order
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        NFrZ   r  r2  rO  r  fetch_paginated_call_dynamicr<  r  r  r  r  r  r  s         r  fetch_closed_orderszkucoin.fetch_closed_orders[	  s      ( !!!!!!!!!88ATV`aa& 	n::;NPVX]_dflmmmmmmmmm00vVVVVVVVVVr  c                    K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S |                     d||||           d{V S )a2  
        fetch all unfilled currently open orders
        :see: https://docs.kucoin.com/spot#list-orders
        :see: https://docs.kucoin.com/spot#list-stop-orders
        :see: https://docs.kucoin.com/spot-hf/#obtain-list-of-active-hf-orders
        :see: https://docs.kucoin.com/spot-hf/#obtain-list-of-filled-hf-orders
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of  open orders structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.till]: end time in ms
        :param bool [params.stop]: True if fetching stop orders
        :param str [params.side]: buy or sell
        :param str [params.type]: limit, market, limit_stop or market_stop
        :param str [params.tradeType]: TRADE for spot trading, MARGIN_TRADE for Margin Trading
        :param int [params.currentPage]: *stop orders only* current page
        :param str [params.orderIds]: *stop orders only* comma seperated order ID list
        :param bool [params.stop]: True if fetching a stop order
        :param bool [params.hf]: False,  # True for hf order
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        NFrv   r  r  r>  r@  s         r  fetch_open_orderszkucoin.fetch_open_ordersv	  s      . !!!!!!!!!88ART^__& 	l::;LfV[]bdjkkkkkkkkk0065%QWXXXXXXXXXr  c                   K   |                                   d{V  i }|                     |dd          }|                     |dd          }|                     |dd          }d}||                     |          }|r$|t	          | j        dz             |d         |d	<   |                     |g d
          }d}	|||d<   |r>||d         |d	<   |                     |                     ||                     d{V }	n|r0| 	                    |                     ||                     d{V }	n| 
                    |                     ||                     d{V }	n|t          | j        dz             ||d<   |r0|                     |                     ||                     d{V }	na|r0|                     |                     ||                     d{V }	n/|                     |                     ||                     d{V }	|                     |	di           }
t!          |
t"                    r|                     |
d          }
|                     |
|          S )a  
        fetch an order
        :see: https://docs.kucoin.com/spot#get-an-order
        :see: https://docs.kucoin.com/spot#get-single-active-order-by-clientoid
        :see: https://docs.kucoin.com/spot#get-single-order-info
        :see: https://docs.kucoin.com/spot#get-single-order-by-clientoid
        :see: https://docs.kucoin.com/spot-hf/#details-of-a-single-hf-order
        :see: https://docs.kucoin.com/spot-hf/#obtain-details-of-a-single-hf-order-using-clientoid
        :param str id: Order id
        :param str symbol: not sent to exchange except for stop orders with clientOid, but used internally by CCXT to filter
        :param dict [params]: exchange specific parameters
        :param bool [params.stop]: True if fetching a stop order
        :param bool [params.hf]: False,  # True for hf order
        :param bool [params.clientOid]: unique order id created by users to identify their orders
        :returns: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  r  r  Fr  z7 fetchOrder() requires a symbol parameter for hf ordersr/   r  )r  r  r  r  z" fetchOrder() requires an order idr  r  r   )rO  rb  r  r  r   r/   rf  (privateGetStopOrderQueryOrderByClientOidrT  &privateGetHfOrdersClientOrderClientOid#privateGetOrderClientOrderClientOidr#   privateGetStopOrderOrderIdprivateGetHfOrdersOrderIdprivateGetOrdersOrderIdr  
isinstancerc  r  r  )r  r/   r  r  rU  r  r  r  r  r  r;  s              r  fetch_orderzkucoin.fetch_order	  s     " !!!!!!!!!**6;PP~~ffe44^^FD%00[[((F 	-~'2k(klll &tGH6#O#O#OPP$#0GK  h%(.tGH%!%!N!Nt{{[bdjOkOk!l!lllllll h!%!L!LT[[Y`bhMiMi!j!jjjjjjj!%!I!I$++V]_eJfJf!g!ggggggg
 z"47-Q#QRRR!#GI \!%!@!@WV\A]A]!^!^^^^^^^ \!%!?!?GU[@\@\!]!]]]]]]]!%!=!=dkk'SY>Z>Z![![[[[[[[~~h;;lD)) 	<??<;;Lf555r  c           	         |                      |d          }|                     |d          }|                      |d          }|                     |dd          }|                      |d          }|d u}|                     |dd          }	|                     |dd	          }
|                      |d
          }d }|
	|
du rd}nd}|r|dk    rd}n|
s|	sd}|rd}|dk    rd}|                     |d          }|                     i d|d|                     |g 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  	createdAtfeeCurrencycancelExistFr  stopTriggeredisActiver  r   Tr  r1  NEW	cancelledcanceledfailrejectedr  r  r/   )r/   r  
newOrderIdr  r  r  r  timeInForcer  r  r  r
  r  r  r  	dealFundsfilleddealSize	remainingr   rr  r*  )r  r  )r*  r   lastTradeTimestampr  trades)
r  r  r  r  r  
safe_ordersafe_string_nsafe_symbolr  r  )r  orderr  r  r   feeCurrencyIdrP  responseStopr  rQ  rR  responseStatusr   r  s                 r  r  zkucoin.parse_order	  s3   t ##E844%%e[99	((>>nnUM5AA''v664'uouEE##E:x@@))%::4! 	%&& %m %$ 	 FV##F$$UK88	  
E 
$$$U,K,K,KLL 
 T--e[AA 
 d&&x==	 

 D$$UF33 
 4++E=AA 
 uj99 
 D$$UF33 
 d&&uf55 
 T%%eW55 
  
 I 
 D$$UK88 
 d&&uj99 
  
  ! 
" Y//# 
& !33MBB((66  "&3 
  
  
4 5  	r  c           	      r   K   d|i}|                      ||||                     ||                     d{V S )aK  
        fetch all the trades made from a single order
        :see: https://docs.kucoin.com/#list-fills
        :see: https://docs.kucoin.com/spot-hf/#transaction-details
        :param str id: order id
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        r  N)fetch_my_tradesrT  )r  r/   r  r  r  r  rU  s          r  fetch_order_tradeszkucoin.fetch_order_trades~
  sQ       r
 ))&%GU[@\@\]]]]]]]]]r  c                   K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S i }|                     |dd          }|r|t	          | j        dz             d}| |                     |          }|d         |d<   |||d	<   | j        d
         }	d}
d}|                     d||          \  }}|r0| 	                    | 
                    ||                     d{V }n|	dk    r7|||d<   |                     | 
                    ||                     d{V }nO|	dk    r2d}
|                     | 
                    ||                     d{V }nt          | j        dz             |                     |di           }d}|
r|}n|                     |dg           }|                     ||||          S )a  
        :see: https://docs.kucoin.com/#list-fills
        :see: https://docs.kucoin.com/spot-hf/#transaction-details
        fetch all trades made by the user
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch entries for
        :param bool [params.hf]: False,  # True for hf order
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        NFrr   r  r  z: fetchMyTrades() requires a symbol parameter for hf ordersr/   r  r3  r  r  r  r  private_get_limit_fillsTz% fetchMyTradesMethod() invalid methodr  r4  )rO  r  r?  r  r   r/   r  r  handle_until_optionprivateGetHfFillsrT  privateGetFillsprivateGetLimitFillsr   r  r  parse_trades)r  r  r  r  r  r  rU  r  r  methodparseResponseDatar  r  r_  s                 r  rh  zkucoin.fetch_my_trades
  s{      !!!!!!!!!88R\]]& 	j::?FTY[`bhiiiiiiiii^^FD%00 	l&.#DG.j$jkkk[[((F &tGH"'GJ34!227GVLL 	S!33DKK4P4PQQQQQQQQHH*** %*	"!11$++gv2N2NOOOOOOOOHH000 !%!66t{{7F7S7STTTTTTTTHH*Q QRRRR ~~h33 	7FF^^D'266F  >>>r  c                 4  K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |dg           }|                     ||||          S )a  
        get the list of most recent trades for a particular symbol
        :see: https://docs.kucoin.com/#get-trade-histories
        :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 Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        Nr  r/   r  )rO  r  publicGetMarketHistoriesrT  r  rp  )	r  r  r  r  r  r  rU  r  r_  s	            r  fetch_tradeszkucoin.fetch_trades
  s       !!!!!!!!!V$$fTl
 66t{{7F7S7STTTTTTTT &"55  >>>r  c                    |                      |d          }|                     ||d          }|                     |dd          }|                      |d          }|                      |d          }|                     |d          }||                     |dz            }n!|                     |d	          }d
|v r||dz  }|                     |dd          }|                     |dd          }	|                      |d          }
d }|                      |d          }|]|                      |d          }|                     |          }||
dk    r|d         n|d         }|||                      |d          d}|                      |d          }|dk    rd }|                     |dd
          }|                     |||||                     |          |d         |||
||	||d|          S )Nr  r  tradeIdr/   r  	liquidityrq  i@B rN  	dealValuer  r  	dealPricer
  r  r  r*  rO  r{  r  r  feeRate)r  r  rater  matchr	  )r  r/   rc  r   rr  r  r  takerOrMakerr  r  r  r  r*  )r  r  rb  r  r  r  
safe_trader  )r  r  r  r  r/   r  r~  r   priceStringr  r  r*  feeCostStringrd  rO  r  r  s                    r  parse_tradezkucoin.parse_trade  s>   Z ##E844!!(FC88y$77""5)44''{;;%%eV44	 )))g*=>>II))%==Iu$$9+@%,	((EE))%BBv..((66$ ,,UMBBM11-@@K"26&..fWoovf~%'((	:: C
 v..7??D''wDD
"Y//X&( " 
  
   	r  c                   K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |dg           }|                     |d          }|                     |d          }||                     ||          |                     |d          |                     |d          d	d	d
S )a[  
        fetch the trading fees for a market
        :see: https://docs.kucoin.com/#actual-fee-rate-of-the-trading-pair
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `fee structure <https://docs.ccxt.com/#/?id=fee-structure>`
        Nr   r/   r  r   r  r  r  T)r  r  r  r  r  r  )	rO  r  privateGetTradeFeesrT  r  r  r  rb  r  )	r  r  r  r  rU  r  r  firstr  s	            r  fetch_trading_feezkucoin.fetch_trading_fee  s      !!!!!!!!!V$$vd|
 11$++gv2N2NOOOOOOOO ~~h33tQ''##E844&&x88%%e^<<%%e^<<
 
 	
r  c                 r  K   |                      ||          \  }}|                                  d{V  |                     |           |                     |          }|d         ||d}|||d<   d}|                     |          \  }}|*|                     |                                          |d<   d}	|                     |ddd          \  }	}|	rd	|d
<   |                     | 	                    ||                     d{V }
| 
                    |
di           }|                     ||          S )a  
        make a withdrawal
        :see: https://docs.kucoin.com/#apply-withdraw-2
        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str tag:
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        Nr/   )r  r  r  r  r  r   r  FINTERNALfeeDeductTyper  )handle_withdraw_tag_and_paramsrO  r  r  rP  rQ  rR  r  privatePostWithdrawalsrT  r  parse_transaction)r  r)  r  r  r  r  r  rU  rA  r  r  r  s               r  r   zkucoin.withdraw  sp      99#vFFV!!!!!!!!!7###==&& 
 
 ?!GFO"AA&IIV"#66{CCIIKKGG
!::6:|]bcc
F 	2'1GO$44T[[&5Q5QRRRRRRRR ~~h33%%dH555r  c                 >    ddddd}|                      |||          S )Nr  pendingfailed)SUCCESS
PROCESSINGWALLET_PROCESSINGFAILUREr  r  r   statusess      r  parse_transaction_statuszkucoin.parse_transaction_status  s4    #!*	
 
 &&999r  c                    |                      |d          }|                     ||          }|                      |d          }|                      |d          }|                      |d          }|U|                    d          }t          |          }	|	dk    r#|!t          |d                   dk    r|d         }|d         }|dnd	}
|                      |d
          }d }|                      |d          }|Ed }|t	          j        ||          }|                     |          |                     |          |d}|                     |dd          }|                     |d          }d|v}|rd|v rdnd	}
||dz  }||dz  }| 	                    |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#S )$Nr  r  r  
walletTxId@r   r   
withdrawalr  r   r*  )r  r|  r  rN  createAt	updatedAtr  isInnerr  r  r/   withdrawalIdr   rr  r  r  	addressToaddressFromr  tagTotagFromtxidr  r:   remark)internalr*  r  )r  r  r  r  r+   
string_divr  r  r  r  rb  r  r4  r  )r  transactionr  rK  r)  r  r  r  	txidPartsnumTxidPartsr  	rawStatusr*  feeCostr|  r   r  isV1r  r  s                       r  r  zkucoin.parse_transaction  sE   V %%k:>>
&&z8<<"";	::!!+x88\::

3Iy>>La?9Q<((1,,"+A,Q<D $||9$$[(;;	"";66D!)'6::))'22))$//  C
 ''[*MM	##K==;. 	)$-$<$<<<9D$%,	"!D.>>+y99{F33
K
$$$[$GG
 
 Y//	

 t..t/?/?W/U/UVV
 w
 
 4
 3
 S
 t
 
 d''//
 D
 D
  d33I>>!
" t''X>>#
$ !)
 
 
 	
r  c                   K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S i }d}| |                     |          }|d         |d<   |||d<   |                     d||          \  }}d}|Q|d	k     rK|                     |d
z            |d<   |                     |                     ||                     d{V }n6|||d<   |                     |                     ||                     d{V }|d         d         }	| 	                    |	|||ddi          S )a  
        fetch all deposits made to an account
        :see: https://docs.kucoin.com/#get-deposit-list
        :see: https://docs.kucoin.com/#get-v1-historical-deposits-list
        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch deposits for
        :param int [limit]: the maximum number of deposits structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch entries for
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        NFr`   r  r/   r  r3  r      |{r  r  r  r4  r  r  )
rO  r  r?  r  rl  r  privateGetHistDepositsrT  privateGetDepositsparse_transactions
r  r)  r  r  r  r  rU  r  r  r;  s
             r  fetch_depositszkucoin.fetch_deposits\  s      !!!!!!!!!88R\]]& 	h::?DRWY^`fggggggggg}}T**H"*4.GJ"'GJ227GVLL!6!6!%!2!254<!@!@GI!88Wf9U9UVVVVVVVVHH %*	"!44T[[&5Q5QRRRRRRRRHN  '0&&|XuefV_M`aaar  c                   K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S i }d}| |                     |          }|d         |d<   |||d<   |                     d||          \  }}d}|Q|d	k     rK|                     |d
z            |d<   |                     |                     ||                     d{V }n6|||d<   |                     |                     ||                     d{V }|d         d         }	| 	                    |	|||ddi          S )a  
        fetch all withdrawals made from an account
        :see: https://docs.kucoin.com/#get-withdrawals-list
        :see: https://docs.kucoin.com/#get-v1-historical-withdrawals-list
        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch withdrawals for
        :param int [limit]: the maximum number of withdrawals structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch entries for
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        NFr   r  r/   r  r3  r  r  r  r  r  r4  r  r  )
rO  r  r?  r  rl  r  privateGetHistWithdrawalsrT  privateGetWithdrawalsr  r  s
             r  fetch_withdrawalszkucoin.fetch_withdrawals  s      !!!!!!!!!88ASU_``& 	k::;MtUZ\acijjjjjjjjj}}T**H"*4.GJ"'GJ227GVLL!6!6!%!2!254<!@!@GI!;;DKKQW<X<XYYYYYYYYHH %*	"!77GV8T8TUUUUUUUUHP  '0&&|XuefVbMcdddr  c                 R   |                                  }|                     |dd          |d<   |                     |dd          |d<   |                     |dd          |d<   |                     |d	          }|                     |d
          }t          j        ||          |d<   |S )NholdBalanceholdusedavailableBalance	availablefreetotalBalancetotal	liabilityinterestdebt)rI  rb  r  r+   
string_add)r  r<  rI  r  r  s        r  parse_balance_helperzkucoin.parse_balance_helper  s    ,,..,,UM6JJ,,U4FTT--e^WMM{33##E:66!,T8<<r  c                 	  K   |                                   d{V  |                     |d          }d}||                     |          }|                     | j        ddd          }|                     |d|          }|                     | j        d          }|                     |||          }|                     |d          }|                     |dd	          }|rd
}|                     |d          }|                     d|          \  }	}
d}i }|	dk    p|dk    }|	dk    p|dk    }|r=||d         |d<   | 	                    | 
                    ||
                     d{V }ns|r0|                     | 
                    ||
                     d{V }nA||d         |d<   ||d<   |                     | 
                    ||
                     d{V }d}|ddd}|rQ|                     |di           }|                     |d|          }t          dt          |                    D ]}||         }|                     |d          }|                     |dd          }|                     |di           }|                     |di           }|                     |                     |d                    }|                     |                     |d                    }i }|                     |          ||<   |                     |          ||<   |                     |          ||<   n|r|                     |di           }|                     |dg           }t          dt          |                    D ]M}||         }|                     |d          }|                     |          }|                     |          ||<   Nn|                     |dg           }t          dt          |                    D ]}||         }|                     |d          }||k    r|                     |d          }|                     |          } |                                 }!|                     |d          |!d<   |                     |d          |!d<   |                     |d          |!d<   |!|| <   |r|n|                     |          }"|"S ) a  
        query for balance and get the amount of funds available for trading or funds locked in orders
        :see: https://www.kucoin.com/docs/rest/account/basic-info/get-account-list-spot-margin-trade_hf
        :see: https://www.kucoin.com/docs/rest/funding/funding-overview/get-account-detail-margin
        :see: https://www.kucoin.com/docs/rest/funding/funding-overview/get-account-detail-isolated-margin
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param dict [params.marginMode]: 'cross' or 'isolated', margin type for fetching margin balance
        :param dict [params.type]: extra parameters specific to the exchange API endpoint
        :param dict [params.hf]: *default if False* if True, the result includes the balance of the high frequency account
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        Nr)  rV   r`  r>   r  r  r  Fr  r  r  r?   r/   balanceCurrencyr  )r  r   rr  r  assetsr   r  _	baseAsset
quoteAssetr   balancer  r  r  holdsr  )rO  r  r  rb  r  r  rf  r  r  privateGetIsolatedAccountsrT  privateGetMarginAccountrH  r  r  r  rb  r  r  safe_balancer  rI  )#r  r  r)  r  r`  rh  r  r  r  r  r,  r  rU  r  r  r  r  r  r  r<  r  r  r  r  baseCode	quoteCode	subResultr   r  rK  	codeInnerbalanceType
codeInner2rI  
returnTypes#                                      r  fetch_balancezkucoin.fetch_balance  sO      !!!!!!!!!//}}T**H((~}V\]]((EE6FGG}MM66**~~fdE22 	D64(( >>~vVV
E*,E$*2Dw&=DH,< 
	R#-5d^)*!<<T[[RW=X=XYYYYYYYYHH 	R!99$++gu:U:UVVVVVVVVHH#&.tn
#"GFO!44T[[%5P5PQQQQQQQQH\ 
 

  #	1>>(FB77D__T8T::F1c&kk** > >q	++E8<<))(D#>>~~e["==ulB??2243C3CD*3U3UVV 33D4D4DUJ4W4WXX		&*&?&?&E&E	(#'+'@'@'G'G	)$!%!2!29!=!=v>  	1>>(FB77D~~dJ;;H1c(mm,, G G"1+!--gzBB
 33J??	$($=$=g$F$Fy!!	G >>(FB77D1c$ii(( 
1 
1q'"..w??$&&!%!1!1':!F!FJ!%!8!8!D!DJ"llnnG'+'7'7'K'KGG$&*&6&6w&L&LGFO&*&6&6w&H&HGFO)0F:&'FVVT->->v-F-F
r  fromAccount	toAccountc                 >  K   |                                   d{V  |                     |          }|                     ||          }|                     |          }|                     |          }	|                     || j                  }
|                     |	| j                  }|dk    r|	dk    rt          | j        dz             |d         |d}d|vr|                                 |d<   | 	                    | 
                    ||                     d{V }|                     |d          }|                     ||          S |d         |d}|
s|rD|                     || j                  r||d	<   d
}|                     |	| j                  r|	|d<   d
}	||d<   |	|d<   d|vr|                                 |d<   |                     | 
                    ||                     d{V }|                     |d          }|                     ||          S )a  
        transfer currency internally between wallets on the same account
        :see: https://docs.kucoin.com/#inner-transfer
        :see: https://docs.kucoin.com/futures/#transfer-funds-to-kucoin-main-account-2
        :see: https://docs.kucoin.com/spot-hf/#internal-funds-transfers-in-high-frequency-trading-accounts
        :param str code: unified currency code
        :param float amount: amount to transfer
        :param str fromAccount: account to transfer from
        :param str toAccount: account to transfer to
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
        Nr  r  zK transfer() only supports transferring from futures account to main accountr/   )r  r  bizNor  fromTagr  toTagfromtor  )rO  r  currency_to_precisionconvert_type_to_accountin_arrayidsr   r/   uuid22futuresPrivatePostTransferOutrT  r  parse_transferr   privatePostAccountsInnerTransfer)r  r)  r  r  r  r  r  requestedAmountfromIdtoIdfromIsolated
toIsolatedrU  r  r  s                  r  r   zkucoin.transfer  se      !!!!!!!!!==&&44T6BB--k::++I66}}VTX66]]422
Zv~~#DG.{${|||$TN) G v%%#';;== !??GU[@\@\]]]]]]]]H2 >>(F33D&&tX666 %TN) G  &z &==22 ()/GI&'F==tx00 &'+GG$%D$GFO GDM6))'+yy{{$!BB4;;wX^C_C_````````H >>(F33D&&tX666r  c           
      N   |                      |d          }|                     |d          }|                     |d          }|                     |d          }|                     |d          }|                     | j        d          }|                     |||          }	|                     |||          }
|                     |dd          |                     ||          ||                     |          |                     |d	          |	|
| 	                    |          |d
	S )NrN  r  r   payAccountTyperecAccountTyper  applyIdr  r  )	r/   r  r   rr  r  r  r  r   r  )
r  r  safe_string_lowerr  r  rb  r  r  r  parse_transfer_status)r  r   r  r   rK  r  accountFromRawaccountToRawr  accountFrom	accountTos              r  r  zkucoin.parse_transfer  s*   F %%h<<	%%h
;;
$$Xx88	//:JKK--h8HII6FGG&&~~~VV$$^\<PP	$$Xy)DD//
HEE"Y//&&x::&"00;;

 

 
	
r  c                 8    ddi}|                      |||          S )Nr  r  r  r  s      r  r  zkucoin.parse_transfer_status/  s(    )
 &&999r  c                     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}|                      |||          S )Nz%Assets Transferred in After Upgradingr   Depositr  
WithdrawalTransferTrade_Exchanger  zKuCoin BonusbonuszReferral Bonusr   RewardszAirdrop/ForkairdropzOther rewardsz
Fee Rebaterebatez
Buy CryptozSell Cryptor{  zPublic Offering PurchasezRefunded Feesr*  zKCS Pay FeeszMargin TradeLoans)r  zInstant ExchangezSub-account transferzLiquidation Feesr  )r  r  typess      r  parse_ledger_entry_typezkucoin.parse_ledger_entry_type5  s   (
3Z(
}(
 -(
 
	(

 g(
 G(
 j(
 w(
 I(
 W(
 ((
 '(
 6(
  '!(
. U/(
0 E1(
2 G3(
4  !($. %E(
 (
 (
R tT222r  c                 V   |                      |d          }|                      |d          }|                     ||          }|                     |d          }d }|                      |d          }|                     |          }	|                      |d          }
|                     |d          }|                     |          }|                      |d          }|                      |d          }d }|h|d	k    rb	 t          j        |          }|                      |d
          }|                      |d          }||}n|}n# t          $ r}|}Y d }~nd }~ww xY wd }|                      |d          }d }|dk    r|}| 	                    |          |d}||
||||	||||d |d ||dS )Nr/   r  r  bizType	directionrN  accountTypecontextr  r  rw  r*  rw  )r  r  )r/   r  rI  referenceIdreferenceAccountr  r  r  r   rr  beforeafterr   r*  r  )
r  r  r  r  r  r  jsonloads	Exceptionr  )r  itemr  r/   rK  r)  r  balanceAfterr  r  r  r   rr  rI  r
  r  r  r  rw  excr*  r  rO  s                          r  parse_ledger_entryzkucoin.parse_ledger_entrya  s    dD))%%dJ77
&&z8<<!!$11""433++G44$$T;77	%%dK88	<<	**""477""433 7b==
&G,,**69==**69==&")KK")K & & &%&""4//c>>K,,W55;OOC"& '" !
 
 	
s   >AE 
EEEc                   K   |                                   d{V  |                                  d{V  d}|                     |dd          \  }}|                     |d          }|                     |d          }|r|                     d||||           d{V S i }|||d<   d}| |                     |          }|d         |d<   |                     d	||          \  }}d}	|                     d|          \  }	}d}
|rb|	0| 	                    | 
                    ||                     d{V }
n_|                     | 
                    ||                     d{V }
n/|                     | 
                    ||                     d{V }
|                     |
d
          }||                     ||||          S |                     |
d
          }|                     |dg           }|                     ||||          S )a  
        :see: https://docs.kucoin.com/#get-account-ledgers
        :see: https://www.kucoin.com/docs/rest/account/basic-info/get-account-ledgers-trade_hf
        :see: https://www.kucoin.com/docs/rest/account/basic-info/get-account-ledgers-margin_hf
        fetch the history of changes, actions done by the user or operations that altered balance of the user
        :param str code: unified currency code, default is None
        :param int [since]: timestamp in ms of the earliest ledger entry, default is None
        :param int [limit]: max number of ledger entrys to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.hf]: default False, when True will fetch ledger entries for the high frequency trading account
        :param int [params.until]: the latest time in ms to fetch entries for
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger-structure>`
        NFrk   r  r  r  r/   r  r  r  r4  )rO  load_accountsr  r  rf  r?  r  rl  r   privateGetHfMarginAccountLedgersrT  privateGetHfAccountsLedgersprivateGetAccountsLedgersr  parse_ledgerr  )r  r)  r  r  r  r  r  rU  r  r  r  dataListr  r4  s                 r  fetch_ledgerzkucoin.fetch_ledger  s|      !!!!!!!!!  """""""""88PZ[[&~~fd++64(( 	f::=$PUW\^deeeeeeeee
 !&GI}}T**H"*4.GJ227GVLL
!??vVV
F 	Z%!%!F!Ft{{SZ\bGcGc!d!ddddddd!%!A!A$++gW]B^B^!_!_______!;;DKKQW<X<XYYYYYYYYHL >>(F33$$XxFFF~~h//tWb11  %???r  c                    |                      | j        di           }|                      ||i           }|                      ||i           }|                     ||| j        d                   }	|                     |d|	          }
|
dk    rd|v r|d         S |
dk    rd|v r|d         S |
dk    rd|v r|d         S |                     |dd          S )Nr  r6   r  r7   r  r  r   )r  r  r  r  )r  r   rq  pathr  configr  apiVersionsmethodVersionsdefaultVersionr6   s              r  calculate_rate_limiter_costz"kucoin.calculate_rate_limiter_cost  s    >>$,
B??nnXsB77VR@@)).$Y@WXX""69nEEd??$<__$&..$<__$&..$<vvq111r  c                    g }t          dt          |                    D ]4}||         }|                     |          }|                    |           5|                     |d          }	|                     |	|||          S )Nr   r   )r  r  parse_borrow_rater  sort_byfilter_by_currency_since_limit)
r  r  r)  r  r  r  r  r  
borrowRatesorteds
             r  parse_borrow_rate_historyz kucoin.parse_borrow_rate_history  s    q#h--(( 	& 	&AA;D//55JMM*%%%%fk222264NNNr  c                     |                      |dd          }|                     |dd                   }|                     |d          }|                     ||          |                     |dd          d||                     |          |d	S )
NrN  r   r      r  dailyIntRatedayRatioi \&)r  r|  periodr   rr  r  )rb  r  r  r  r]  r  )r  r  r  timestampIdr   rK  s         r  r&  zkucoin.parse_borrow_rate"  s    $ (({KHH%%k!B$&788	%%dJ77
//
HEE&&t^ZHH"Y//
 
 	
r  c                 P  K   |                                   d{V  d}|                     d|          \  }}|d}i }d}| |                     |          }	|	d         |d<   |dk    r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |di           }
|dk    r|                     |
dg           n|                     |
d	g           }|                     |d          S )
a  
        fetch the interest owed by the user for borrowing currency for margin trading
        :see: https://docs.kucoin.com/#get-repay-record
        :see: https://docs.kucoin.com/#query-isolated-margin-account-info
        :param str code: unified currency code
        :param str symbol: unified market symbol, required for isolated margin
        :param int [since]: the earliest time in ms to fetch borrrow interest for
        :param int [limit]: the maximum number of structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.marginMode]: 'cross' or 'isolated' default is 'cross'
        :returns dict[]: a list of `borrow interest structures <https://docs.ccxt.com/#/?id=borrow-interest-structure>`
        NrW   r  r/   quoteCurrencyr  r  r  r   )	rO  r  r  r  rT  privateGetMarginAccountsr  r  parse_borrow_interests)r  r)  r  r  r  r  r  rU  r  r  r  r  s               r  fetch_borrow_interestzkucoin.fetch_borrow_interest@  sd      !!!!!!!!!
!??@UW]^^
F J}}T**H'/~GO$##!<<T[[RX=Y=YZZZZZZZZHH!::4;;wPV;W;WXXXXXXXXHB ~~h338Bj8P8Ph333W[WeWefjlvxzW{W{**64888r  c           
         |                      |d          }|dnd}|                     ||          }|                      |d          }|                     |d          }|                     |di           }d }d }	d }
|dk    rC|                     |d          }|                     |d          }	|                      |d          }
nB|                     |d          }|                     |d	          }	|                      |d          }
|||                     |
          |	|                     |d
          |||                     |          |d	S )Nr  r  r  rN  r  r  r  r  accruedInterestr.  )	r  r  r  r  interestRateamountBorrowedr   rr  r  )r  r  r  r  r  r  r  )r  r  r  r  r  r  r   isolatedBaser:  r  rK  s              r  parse_borrow_interestzkucoin.parse_borrow_interest  sk   Z ##D(33!)!1WW

!!(F33!!&(33%%dK88	~~dK<<
##!--lKHHN''jAAH)),
CCJJ!--dK@@N''.?@@H))$
;;J$//
;;  ,,T>BB,"Y//

 

 
	
r  c                   K   |                                   d{V  |                     d|          }|                     |dd          }|dk    }d|i}|||d<   |                     d||          \  }}|||d	<   |                     |                     ||                     d{V }	|                     |	d
          }
|                     |
d          }|                     ||||          S )a  
        retrieves a history of a multiple currencies borrow interest rate at specific time slots, returns all currencies if no symbols passed, default is None
        :see: https://www.kucoin.com/docs/rest/margin-trading/margin-trading-v3-/get-cross-isolated-margin-interest-records
        :param str[]|None codes: list of unified currency codes, default is None
        :param int [since]: timestamp in ms of the earliest borrowRate, default is None
        :param int [limit]: max number of borrow rate prices to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.marginMode]: 'cross' or 'isolated' default is 'cross'
        :param int [params.until]: the latest time in ms to fetch entries for
        :returns dict: a dictionary of `borrow rate structures <https://docs.ccxt.com/#/?id=borrow-rate-structure>` indexed by the market symbol
        NrX   r   r  r  
isIsolated	startTimeendTimer3  r  r4  )	rO  r  r  rl  privateGetMarginInterestrT  r  r  parse_borrow_rate_histories)r  codesr  r  r  r  r  r>  rU  r  r  rowss               r  fetch_borrow_rate_historiesz"kucoin.fetch_borrow_rate_histories  s"      !!!!!!!!!99:TV\]]%%lAw??
 J.
*
 #(GK 229gvNN"'GJ66t{{7F7S7STTTTTTTT* ~~h//~~dG,,//eUEJJJr  c                   K   |                                   d{V  |                     d|          }|                     |dd          }|dk    }|                     |          }||d         d}	|||	d<   |                     d	|	|          \  }	}|||	d
<   |                     |                     |	|                     d{V }
|                     |
d          }|                     |d          }| 	                    ||||          S )a@  
        retrieves a history of a currencies borrow interest rate at specific time slots
        :see: https://www.kucoin.com/docs/rest/margin-trading/margin-trading-v3-/get-cross-isolated-margin-interest-records
        :param str code: unified currency code
        :param int [since]: timestamp for the earliest borrow rate
        :param int [limit]: the maximum number of `borrow rate structures <https://docs.ccxt.com/#/?id=borrow-rate-structure>` to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.marginMode]: 'cross' or 'isolated' default is 'cross'
        :param int [params.until]: the latest time in ms to fetch entries for
        :returns dict[]: an array of `borrow rate structures <https://docs.ccxt.com/#/?id=borrow-rate-structure>`
        NrX   r   r  r  r/   )r>  r  r?  r@  r3  r  r4  )
rO  r  r  r  rl  rA  rT  r  r  r+  )r  r)  r  r  r  r  r  r>  r  rU  r  r  rD  s                r  fetch_borrow_rate_historyz kucoin.fetch_borrow_rate_history  s=      !!!!!!!!!99:TV\]]%%lAw??
 J.
==&&$ 
 
 #(GK 229gvNN"'GJ66t{{7F7S7STTTTTTTT* ~~h//~~dG,,--dD%GGGr  c                 "   i }t          dt          |                    D ]}||         }|                     |                     |d                    }||                     ||          r9||vrg ||<   |                     |          }	||                             |	           t          |                                          }
t          dt          |
                    D ]+}|
|         }| 	                    ||         |||          ||<   ,|S )Nr   r  )
r  r  r  r  r  r&  r  rc  rd  r(  )r  r  rC  r  r  borrowRateHistoriesr  r  r)  borrowRateStructurerd  s              r  rB  z"kucoin.parse_borrow_rate_historiesM  s*    !q#h--(( 	F 	FAA;D**4+;+;D*+M+MNND}dE : :} 33302'-&*&<&<T&B&B##D)001DEEE',,..//q#d))$$ 	{ 	{A7D(,(K(KL_`dLegkmrty(z(z%%""r  c                 \  K   |                                   d{V  |                     |          }|d         |                     ||          dd}|                     |                     ||                     d{V }|                     |di           }|                     ||          S )a  
        create a loan to borrow margin
        :see: https://docs.kucoin.com/#1-margin-borrowing
        :param str code: unified currency code of the currency to borrow
        :param float amount: the amount to borrow
        :param dict [params]: extra parameters specific to the exchange API endpoints
        :param str [params.timeInForce]: either IOC or FOK
        :returns dict: a `margin loan structure <https://docs.ccxt.com/#/?id=margin-loan-structure>`
        Nr/   FOK)r  r
  rY  r  )rO  r  r  privatePostMarginBorrowrT  r  parse_margin_loanr  r)  r  r  r  rU  r  r  s           r  borrow_cross_marginzkucoin.borrow_cross_marging  s       !!!!!!!!!==&& ..tV<< 
 

 55dkk'66R6RSSSSSSSS ~~h33%%dH555r  c                   K   |                                   d{V  |                     |          }|                     |          }|d         |                     ||          |d         ddd}|                     |                     ||                     d{V }|                     |di           }	|                     |	|          S )a*  
        create a loan to borrow margin
        :see: https://docs.kucoin.com/#1-margin-borrowing
        :param str symbol: unified market symbol, required for isolated margin
        :param str code: unified currency code of the currency to borrow
        :param float amount: the amount to borrow
        :param dict [params]: extra parameters specific to the exchange API endpoints
        :param str [params.timeInForce]: either IOC or FOK
        :returns dict: a `margin loan structure <https://docs.ccxt.com/#/?id=margin-loan-structure>`
        Nr/   rL  T)r  r
  r  rY  r>  r  )rO  r  r  r  rM  rT  r  rN  
r  r  r)  r  r  r  r  rU  r  r  s
             r  borrow_isolated_marginzkucoin.borrow_isolated_margin  s       !!!!!!!!!V$$==&& ..tV<<Tl 
 
 55dkk'66R6RSSSSSSSS ~~h33%%dH555r  c                 Z  K   |                                   d{V  |                     |          }|d         |                     ||          d}|                     |                     ||                     d{V }|                     |di           }|                     ||          S )a  
        repay borrowed margin and interest
        :see: https://docs.kucoin.com/#2-repayment
        :param str code: unified currency code of the currency to repay
        :param float amount: the amount to repay
        :param dict [params]: extra parameters specific to the exchange API endpoints
        :returns dict: a `margin loan structure <https://docs.ccxt.com/#/?id=margin-loan-structure>`
        Nr/   )r  r
  r  )rO  r  r  privatePostMarginRepayrT  r  rN  rO  s           r  repay_cross_marginzkucoin.repay_cross_margin  s       !!!!!!!!!==&& ..tV<<
 
 44T[[&5Q5QRRRRRRRR ~~h33%%dH555r  c                   K   |                                   d{V  |                     |          }|                     |          }|d         |                     ||          |d         dd}|                     |                     ||                     d{V }|                     |di           }	|                     |	|          S )a  
        repay borrowed margin and interest
        :see: https://docs.kucoin.com/#2-repayment
        :param str symbol: unified market symbol
        :param str code: unified currency code of the currency to repay
        :param float amount: the amount to repay
        :param dict [params]: extra parameters specific to the exchange API endpoints
        :returns dict: a `margin loan structure <https://docs.ccxt.com/#/?id=margin-loan-structure>`
        Nr/   T)r  r
  r  r>  r  )rO  r  r  r  rU  rT  r  rN  rR  s
             r  repay_isolated_marginzkucoin.repay_isolated_margin  s       !!!!!!!!!V$$==&& ..tV<<Tl	
 
 44T[[&5Q5QRRRRRRRR ~~h33%%dH555r  c                    |                                  }|                     |d          }|                     |d          |                     ||          |                     |d          d ||                     |          |dS )Nr  orderNo
actualSize)r/   r  r  r  r   rr  r  )r  r  r  r  r  )r  r  r  r   rK  s        r  rN  zkucoin.parse_margin_loan  s     %%''	%%dJ77
""433//
HEE&&t\::"Y//
 
 	
r  rC  c                    K   |                                   d{V  |                     |           d{V }|                     |dg           }|                     ||d          S )a  
        fetch deposit and withdraw fees - *IMPORTANT* use fetchDepositWithdrawFee to get more in-depth info
        :see: https://docs.kucoin.com/#get-currencies
        :param str[]|None codes: list of unified currency codes
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `fee structures <https://docs.ccxt.com/#/?id=fee-structure>`
        Nr  r  )rO  r.  r  parse_deposit_withdraw_fees)r  rC  r  r  r  s        r  fetch_deposit_withdraw_feesz"kucoin.fetch_deposit_withdraw_fees  s       !!!!!!!!!11&99999999& ~~h33//eZHHHr  r   r  c                    |                      | j        di           }|                      ||i           }|                      ||i           }	|                     |	|| j        d                   }
|                     |d|
          }|                     |d          }d|z   dz   |                     ||          z   }|dk    rd|                     ||          z   }|                     ||                     |                    }d}||ni }| j        d         |         }|                     |          sD|dk    s|d	k    r|d
|                     |          z   z  }n| 	                    |          }|}d|d<   ||z   }|dk    }|dk    }|dk    }|s|s|r*| 
                                 t          |                                           }|                     d| j        |d|          }|                     |d          }|dk    rX|                     |                     | j                  |                     | j                  t&          j        d          }||d<   n
| j        |d<   ||z   |z   |z   }|                     |                     |          |                     | j                  t&          j        d          }||d<   |                      | j        di           }|r|                     |d|          n|                     |d|          }|                     |d          }|                     |dd          }|a|_||z   | j        z   }|                     |                     |          |                     |          t&          j        d          }||d<   ||d<   |r|                     |d          }|||d<   ||||d S )!Nr  r6   z/api/r  r   r  r   r  r  ?zapplication/jsonzContent-Typer   r   r   r+  )KC-API-KEY-VERSIONz
KC-API-KEYzKC-API-TIMESTAMPra  base64zKC-API-PASSPHRASEzKC-API-SIGNr  rA   r>   r/   r   r  zKC-API-PARTNER-SIGNzKC-API-PARTNERr0   zKC-BROKER-NAME)r  rq  bodyheaders)r  r  r  rf  implode_paramsextract_paramsr   is_empty	rawencoder  r  strr  rT  r   hmacencoder   r   hashlibsha256r  rb  )r  r  r   rq  r  rd  rc  r  r!  r"  r#  r6   endpointr,  endpartr  isFuturePrivate	isPrivateisBrokerr   apiKeyVersion
passphrasepayload	signaturer  	partnerIdpartnerSecretpartnerPayloadpartnerSignature
brokerNames                                 r  signzkucoin.sign!  s	    >>$,
B??nnXsB77VR@@)).$Y@WXX""69nEE69--W$s*T-@-@v-N-NN-T00v>>>H		&$"5"5d";";<<%1''is#}}U## 	=%Vx%7%7C$.."7"777yy''*<'Hn"22I%	8O 	; 	;8 	;++---DJJLL))Ikk&)"k$-# # 	 G
 !,,W6JKKM##!YYt{{4='A'A4;;t{C[C[]d]kmuvv
/9+,,/3}+,&(83g=G		$++g"6"6DK8P8PRYR`bjkkI%.GM"nnT\9bAAGET  DdoogxAAAZ^ZiZijqsy  |C  [D  [DG(($77I ..w%HHM%M,E!*Y!6!D#'99T[[-H-H$++VcJdJdfmftv~## 1A-.,5() ;!--gv>>
)0:G,-fdwOOOr  c
                    |s$|                      | j        d         ||           d S |                     |d          }
|                     |ddd          }| j        dz   |z   }|                     | j        d         ||           |                     | j        d         |
|           |                      | j        d         ||           |
dk    r|
d	k    rt          |          d S )
Nru  r)  msgr  r   rt  200000ry  )throw_broadly_matched_exceptionr  r  rb  r/   throw_exactly_matched_exceptionr   )r  r)  reasonr  rq  rd  rc  r  requestHeadersrequestBody	errorCodemessagefeedbacks                r  handle_errorszkucoin.handle_errors_  s     	001I4QUVVV4 $$Xv66	$$XufbAA7S=7*,,T_W-EwPXYYY,,T_W-EyRZ[[[,,T_W-EtXVVV  Y%%7%7)))tr  r  )c__name__
__module____qualname__r  r  r  r  r   r
   r  r   rF  r   rL  ri  rW  r[  r   rY  ri  r   r  r   r   r  r  rc  r  r	   r  r  r  r  r  r   r  r  r   r   floatr   r  r  r  r  r   r  r  r  r  r   r%  r-  r<  r   rA  rC  rL  r  ri  rh  r   ru  r  r   r  r   r  r   r  r  r  r  r   r  r   r   r  r  r  r  r  r$  r+  r&  r6  r<  rE  rG  rB  rP  rS  rV  rX  rN  r^  r|  r  __classcell__)r  s   @r  r-   r-   "   s/       Q Q Q Q Qf# # # ') 3 3 3 3" )+ 
 
 
 
6 *, G GV G G G GR -/ V V: V V V Vp +- . .g . . . .` =? 
 
 
 
 
 
6 BD &? &?S &? &? &? &?P* * * * * *XP P P"X X6 XV X X X Xt 6:" 1G 1G7 1G 1G 1G 1G 1Gf 68 %; %; %;F %; %; %; %;N
 
 
4 
 
 
 
* 8<$]ajl 2H 2H 2HC 2HWZ 2Hquvzq{ 2H 2H 2H 2Hh >@ : : : : : :2 =? : : : : : :@
 
h 
 
 
 
& JL $0 $0S $0 $0 $0 $0L @DB ? ?S ? ?S\ ? ? ? ?B> > > mqy{ M. M. M.I M.Y M.X] M.fi M. M. M. M.^ eg S S# SY SV[ S S S S XZ 
U 
Uc 
U 
U 
U 
U 
U Y[ 
V 
Vs 
V% 
V 
V 
V 
V FH J' J'$|*< J' J' J' J'Xs     os{} 7, 7,3 7,i 7,y 7,Z_ 7,hk 7, 7, 7, 7,r fjx|  FH &. &.3 &. &.9 &.I &._b &.ru &. &. &. &.P 9=R , ,S ,# , , , ,\ 59 % %c % % % %N BFTXgktv j? j?3 j?c j?ad j? j? j? j?X 7;\`ik W W W3 WVY Wptuzp{ W W W W6 59tZ^gi Y Yc Y YTW Ynrsxny Y Y Y Y< 8<B 96 96C 96 96 96 96 96vm m m5 m m m m^ ?CQUdhqs ^ ^3 ^ ^3 ^^a ^ ^ ^ ^" 37TX\eg _? _?C _?s _?RU _? _? _? _?B <@d[] &? &? &?S &? &?bfglbm &? &? &? &?P{ { {5 { { { {z ;= $
 $
c $
AT $
 $
 $
 $
L EIQS .6 .63 .6 .6 .6 .6 .6`: : :f
 f
x f
; f
 f
 f
 f
P 04$UYbd Jb Jb JbC Jbs Jbimnyiz Jb Jb Jb JbX 37TX\eg Ke KeC Kes KeRU Kelpq|l} Ke Ke Ke KeZ   *, b b b b b bH ac S7 S73 S7 S7C S7TW S7gt S7 S7 S7 S7j5
 5
 5
 5
 5
 5
n: : :*3 *3 *3XL
 L
 L
 L
 L
 L
\ .2SW`b Z@ Z@s Z@# Z@S Z@ Z@ Z@ Z@x MO 2 2 2 2O O O
 
 
 
 
 
< 7;$]apt} ]9 ]9 ]9C ]9WZ ]9jm ]9 ]9 ]9 ]9~H
 H
& H
 H
 H
 H
T 7;\`ik /K /K3 /KVY /K /K /K /Kb GKY]fh 1H 1HC 1H 1HSV 1H 1H 1H 1Hf# # #4 JL 6 6c 65 6 6 6 6B Z\ #6 #63 #6c #65 #6 #6 #6 #6J BD 6 6S 6 6 6 6> RT !6 !6# !6S !6 !6 !6 !6F
 
 
 
 
 
& BFb I Iw I I I I> &eBSW <P <P <P <P|      r  r-   )5 ccxt.async_support.base.exchanger   ccxt.abstract.kucoinr   r0  rl  r  r  ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   typingr   ccxt.base.errorsr   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   ccxt.base.decimal_to_precisionr)   r*   ccxt.base.preciser+   r-    r  r  <module>r     s   6 5 5 5 5 5 , , , , , ,     c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c       * * * * * * 0 0 0 0 0 0 - - - - - - - - - - - - . . . . . . ' ' ' ' ' ' & & & & & & . . . . . . + + + + + + ) ) ) ) ) ) * * * * * * ) ) ) ) ) ) . . . . . . 1 1 1 1 1 1 ) ) ) ) ) ) 3 3 3 3 3 3 4 4 4 4 4 4 % % % % % %OE OE OE OE OEX{ OE OE OE OE OEr  