
    iF                       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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.m/Z/ d dl.m0Z0 d dl1m2Z2  G d dee          Z3d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    Q/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/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                 X    |                      |          }|                     |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
        data)publicGetTimestampsafe_integer)r  paramsresponses      r  
fetch_timezkucoin.fetch_time  s/     **622   6222r  c                     |                      |          }|                     |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>`
        r  r   openokmaintenanceN)r   updatedetaurlinfo)publicGetStatus	safe_dictsafe_string)r  r  r  r  r   s        r  fetch_statuszkucoin.fetch_status  so     ''// ~~h33!!$11%//ddm
 
 	
r  returnc                    |                      |          }|                     |d          }|                     | j        di           }|                     |dd          }i }|r|                     |          }|                     |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
        r  rp   r  Tr   symbolr   r  makerFeeRatetakerFeeRatemakerCoefficienttakerCoefficientr/   /basequotesettleN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    ((004 ~~h//..~rBB>>'3EtLL 	E"<<VDDO: 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                    g }|                     |                     |                     |                     |                     ddd                     |}|                     |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]   'webExchangeGetCurrencyCurrencyChainInfoTr   r  r   currencyfullNameN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_endpointr  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_currenciesn  s    0088999> 	//0AClnrsstttF 	!^^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           	         |                      |          }|                     |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
        r  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     **6220 ~~h33q#d))$$ 	 	A1gG(($77I))':>>J**:66D##GV44DMM       r  r)  c                    |                                   |                     |          }d|d         i}d}|                     |          \  }}|*|                     |                                          |d<   |                     |                     ||                    }|                     |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>`
        r  r/   Nr  r  withdrawMinFee)r  r   r  )	load_marketsr  handle_network_code_and_paramsnetwork_code_to_idlowerprivateGetWithdrawalsQuotasextendr  r  )	r  r)  r  r  requestr?  r  r  withdrawFeess	            r  fetch_transaction_feezkucoin.fetch_transaction_fee6  s     	==&&
 "AA&IIV"#66{CCIIKKGG33DKK4P4PQQ~~h33!--d4DEET$
 
 	
r  c                    |                                   |                     |          }d|d         i}d}|                     |          \  }}|*|                     |                                          |d<   |                     |                     ||                    }|                     |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>`
        r  r/   Nr  r  )	rM  r  rN  rO  rP  rQ  rR  r  parse_deposit_withdraw_feer  r)  r  r  rS  r?  r  r  s           r  fetch_deposit_withdraw_feez!kucoin.fetch_deposit_withdraw_feeQ  s     	==&&
 "AA&IIV"#66{CCIIKKGG33DKK4P4PQQ& ~~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$  rL  r   r*  Fr  r  r)  r(  r  )r  safe_number_2r  r2  )r  r*  r  r  r!  	networkIdr?  s          r  rW  z!kucoin.parse_deposit_withdraw_feey  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  rb  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  r`  safe_marketsafe_integer_2safe_tickeriso8601)
r  r   r  r  rk  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                    |                                   |                     |          }|                     |          }|                     |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>`
        r  r   ro  r   r  )rM  market_symbolsr	  r  r  r  r  r  r  r  filter_by_array_tickers)r  r   r  r  r  r  ro  r  r  r   r  s              r  fetch_tickerszkucoin.fetch_tickers  s    	%%g..11&99: ~~h33..x44  v..q#g,,'' 	( 	(A!%GAJv&&wqz22F%%fh77F!!'v++FHgFFFr  r  c                     |                                   |                     |          }d|d         i}|                     |                     ||                    }|                     |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>`
        r  r/   r  )rM  r  publicGetMarketStatsrR  r  )r  r  r  r  rS  r  s         r  fetch_tickerzkucoin.fetch_tickerC  sw     	V$$fTl
 ,,T[[&-I-IJJ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_ohlcvj  s     q))UA&&UA&&UA&&UA&&UA&&
 	
r  r   sincelimitc           	         |                                   d}|                     |dd          \  }}|r|                     d|||||d          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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
        Frs   paginatei  r/   )r  r    NstartAtfetchOHLCVLimitendAtr  )rM  handle_option_and_params"fetch_paginated_call_deterministicr  r  r   parse_timeframer  parse_to_intintmathfloorr  r  sumpublicGetMarketCandlesrR  r  parse_ohlcvs)r  r  	timeframer  r  r  r  r  r  rS  durationr  r  r  s                 r  fetch_ohlcvzkucoin.fetch_ohlcv  s    	88zZZ& 	x::<QVX]_hjprvwww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..t{{7F/K/KLL ~~h33  vy%GGGr  c                    |                                   |                     |          }d|d         i}d}|                     |          \  }}|*|                     |                                          |d<   |                     |                     ||                    }|                     |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>`
        r  r/   Nr  r  )	rM  r  rN  rO  rP  privatePostDepositAddressesrR  r  parse_deposit_addressrX  s           r  create_deposit_addresszkucoin.create_deposit_address  s     	==&&
 "AA&IIV"#66{CCIIKKGG33DKK4P4PQQ ~~h33))$999r  c                 ~   |                                   |                     |          }d|d         i}d}|                     |          \  }}|*|                     |                                          |d<   | j        d         d         d         d         }d	| j        d         d         d         d<   |                     |                     ||                    }|| 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>`
        r  r/   Nr  r  r   r  r   r  r  zr fetchDepositAddress() returned an empty response, you might try to run createDepositAddress() first and try again)rM  r  rN  rO  rP  r  privateGetDepositAddressesrR  
safe_valuer   r/   r  )	r  r)  r  r  rS  r?  r6   r  r  s	            r  fetch_deposit_addresszkucoin.fetch_deposit_address  sL    	==&&
 "AA&IIV"#66{CCIIKKGG,z*95e<=PQJNZ +E23FG224;;w3O3OPP 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_addressr2  )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                    |                                   |                     |          }d|d         i}| j        d         d         d         d         }d| j        d         d         d         d<   |                     |                     ||                    }|| 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>`
        r  r/   r  r   r  r   r7   r  r)  Fr  )rM  r  r  r  rR  r  parse_deposit_addressesr
  )	r  r)  r  r  rS  r6   r  r  parseds	            r  "fetch_deposit_addresses_by_networkz)kucoin.fetch_deposit_addresses_by_network  s    	==&&
 ,z*95e<=PQJNZ +E23FG224;;w3O3OPP  KRZ +E23FG&"55--fx7G6H%R
   }}VY///r  c           
         |                                   |                     |          }|                     |dd          }d|d         i}|                     d          }d}|r|i|dk    r9||d<   |)|dk    s|dk    r||d	<   nt	          | j        d
z             |r|nd|d	<   |                     |                     ||                    }n)|                     |                     ||                    }| 	                    |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
        levelr   r  r/   FNr   d   r  z2 fetchOrderBook() limit argument must be 20 or 100r  ro  bidsasksr   sequencer  )rM  r  r  check_required_credentialsr   r/   'publicGetMarketOrderbookLevelLevelLimitrR  privateGetMarketOrderbookLevel2r  parse_order_book)r  r  r  r  r  r  rS  isAuthenticatedr  r  r   	orderbooks               r  fetch_order_bookzkucoin.fetch_order_book%  s    	V$$!!&'155VD\*99%@@ 	Z%"3zz#( $#+0((+DG6j,jkkk,1#:55s CCDKKPWY_D`D`aaHH;;DKKQW<X<XYYH@ ~~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_pricesf  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                 ^   |                                   |                     |          }|                     |dd          }|                     |d          }|                     |dd          }	|                     |          \  }
}}|                     |d          }|
p|p|}|                     d|          }|                     |d          }|dk    p|du}|                     ||||||          }d}|r.|r|                     |          }ns| 	                    |          }n]|	r| 
                    |          }nE|r|                     |          }n-|r|                     |          }n|                     |          }|                     |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>`
        testFr  	tradeTyperM   r   r  Nr  )rM  r  r  rd  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_orderp  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[[ 	< D::<HH55lCC 	<//==HH 	<00>>HH 	<22<@@HH--l;;H ~~h33f---r  r  c                 h    |                                   ||d<   |                     |d||d|          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>`
        r  r  N)rM  r  )r  r  r  r  r  s        r  create_market_order_with_costz$kucoin.create_market_order_with_cost  s=     	v  4tVLLLr  c                 Z    |                                   |                     |d||          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>`
        rt  rM  r  r  r  r  r  s       r  !create_market_buy_order_with_costz(kucoin.create_market_buy_order_with_cost  s0     	11&%vNNNr  c                 Z    |                                   |                     |d||          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>`
        ry  r  r  s       r  "create_market_sell_order_with_costz)kucoin.create_market_sell_order_with_cost  s0     	11&&$OOOr  r   c           	      6   |                                   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}|r*|                     |                     ||                    }n)|                     |                     ||                    }|                     |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  )rM  r  r  r  r   r/   r  r  r  r  r  rd  privatePostHfOrdersMultirR  privatePostOrdersMultir  r  parse_orders)r  r   r  ordersRequestsr  r  rawOrderr  r  r  r  r  orderParamsr  r  rS  r  r  r  s                      r  create_orderszkucoin.create_orders  s'    	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(( 	Q44T[[&5Q5QRRHH224;;w3O3OPPH> ~~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_precision1  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  rt  r:  lossstopr  z= createOrder does not support isolated margin for stop ordersr  r  marginModelFTpostOnly)r  r`  uuidrd  r[  r  r  amount_to_precisionprice_to_precisionr  r  r   r/   r  handle_post_onlyrR  )r  r  r  r  r  r  r  r  r  rS  quoteAmountamountString
costStringr  r  r  r  r  r  r  r  s                        r  r  zkucoin.create_order_request8  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                    |                                   |                     |          }d|d         i}	|                     |dd          }
|
|
|	d<   n||	d<   ||                     ||          |	d<   ||                     ||          |	d<   |                     |                     |	|                    }|                     |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>`
        r  r/   r  r  NorderIdnewSizenewPricer  )	rM  r  r`  r  r  privatePostHfOrdersAlterrR  r  r  )r  r/   r  r  r  r  r  r  r  rS  r  r  r  s                r  
edit_orderzkucoin.edit_orderq  s     	V$$fTl
 **6;PP$#0GK  !#GI!%!9!9&&!I!IGI"&"9"9&%"H"HGJ00Wf1M1MNN ~~h33f---r  c                    |                                   i }|                     |dd          }|                     |ddd          }|                     |dd          }|r9|t	          | j        dz             |                     |          }|d	         |d
<   d}	|                     |g d          }|||d<   |r*|                     | 	                    ||                    }	n|r*| 
                    | 	                    ||                    }	n|                     | 	                    ||                    }	n||d<   |r*|                     | 	                    ||                    }	nU|r*|                     | 	                    ||                    }	n)|                     | 	                    ||                    }	|	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
        r  r  r
  triggerFr  Nz8 cancelOrder() requires a symbol parameter for hf ordersr/   r  )r  r  r
  r  r  r  )rM  r`  safe_bool_2r  r   r/   r  rd  ,privateDeleteStopOrderCancelOrderByClientOidrR  )privateDeleteHfOrdersClientOrderClientOid&privateDeleteOrderClientOrderClientOidprivateDeleteStopOrderOrderIdprivateDeleteHfOrdersOrderIdprivateDeleteOrdersOrderId)
r  r/   r  r  rS  r  r
  r  r  r  s
             r  cancel_orderzkucoin.cancel_order  s     	**6;PP	5AA^^FD%00 	-~'2l(lmmm[[((F &tGH6#Z#Z#Z[[$#0GK  eLLT[[Y`bhMiMijj eII$++V]_eJfJfggFFt{{SZ\bGcGcdd!#GI Y==dkk'SY>Z>Z[[ Y<<T[[RX=Y=YZZ::4;;wPV;W;WXXr  c                    |                                   i }|                     |dd          }|                     |dd          }|                     |ddg          }|                     d|          \  }}||                     |          |d<   |5| j        d         |         |d<   |d	k    r|rt          | j        d
z             d}|r*|                     | 	                    ||                    }n|rV|*| 
                    | 	                    ||                    }nS|                     | 	                    ||                    }n)|                     | 	                    ||                    }|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
        r
  Fr  rE   Nr  r  r  r  zA cancelAllOrders does not support isolated margin for stop orders)rM  r  rd  r  	market_idr  r   r/   privateDeleteStopOrderCancelrR  privateDeleteHfOrdersCancelAllprivateDeleteHfOrdersprivateDeleteOrders)	r  r  r  rS  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 	M88We9T9TUUHH 	M~>>t{{7TY?Z?Z[[55dkk'56Q6QRR//GU0K0KLLHr  c                    |                                   |                                }|                     |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}|r*| 	                    | 
                    ||                    }n|	r`|d	k    r*|                     | 
                    ||                    }nY|dk    r)|                     | 
                    ||                    }n)|                     | 
                    ||                    }|                     |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>`
        untiltillr
  Fr  )r
  r  r.  r-  rz   r  r  closeddoner   Nr/   r  r  pageSizer  r  r  r  r  items)rM  rP  r  r  rd  r  r  r  r  privateGetStopOrderrR  privateGetHfOrdersActiveprivateGetHfOrdersDoneprivateGetOrdersr  r  r  )r  r   r  r  r  r  lowercaseStatusr-  r
  r  r  r*  rS  r  r  listDataresponseDatar   s                     r  fetch_orders_by_statuszkucoin.fetch_orders_by_status  sz   . 	 ,,..##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 	J//GU0K0KLLHH 	J(**88We9T9TUU F**66t{{7E7R7RSS,,T[[%-H-HIIHX >>(F33$$XvueDDD~~h;;gr::  >>>r  c                     |                                   d}|                     |dd          \  }}|r|                     d||||          S |                     d||||          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>`
        FrZ   r  r0  rM  r  fetch_paginated_call_dynamicr:  r  r  r  r  r  r  s         r  fetch_closed_orderszkucoin.fetch_closed_ordersZ	  s~    ( 	88ATV`aa& 	h445H&RWY^`fggg**665%PPPr  c                     |                                   d}|                     |dd          \  }}|r|                     d||||          S |                     d||||          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>`
        Frv   r  r  r<  r>  s         r  fetch_open_orderszkucoin.fetch_open_ordersu	  s~    . 	88ART^__& 	f445FPUW\^deee**8VUE6RRRr  c                    |                                   i }|                     |dd          }|                     |dd          }|                     |dd          }d}||                     |          }|r$|t	          | j        dz             |d         |d	<   |                     |g d
          }d}	|||d<   |r7||d         |d	<   |                     |                     ||                    }	n|r*| 	                    |                     ||                    }	n| 
                    |                     ||                    }	n|t          | j        dz             ||d<   |r*|                     |                     ||                    }	nU|r*|                     |                     ||                    }	n)|                     |                     ||                    }	|                     |	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>`
        r  r  r
  Fr  Nz7 fetchOrder() requires a symbol parameter for hf ordersr/   r  )r
  r  r  r  z" fetchOrder() requires an order idr  r  r   )rM  r`  r  r  r   r/   rd  (privateGetStopOrderQueryOrderByClientOidrR  &privateGetHfOrdersClientOrderClientOid#privateGetOrderClientOrderClientOidr#   privateGetStopOrderOrderIdprivateGetHfOrdersOrderIdprivateGetOrdersOrderIdr  
isinstancera  r  r  )r  r/   r  r  rS  r  r
  r  r  r  r9  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  b%(.tGH%HHU\^dIeIeff bFFt{{SZ\bGcGcddCCDKKPWY_D`D`aa
 z"47-Q#QRRR!#GI V::4;;wPV;W;WXX V99$++gv:V:VWW77GV8T8TUU~~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  r/  NEW	cancelledcanceledfailrejectedr  r  r/   )r/   r  
newOrderIdr  r  r  r  timeInForcer  r  r  r  r  r  r  	dealFundsfilleddealSize	remainingr   rp  r*  )r  r  )r*  r   lastTradeTimestampr  trades)
r  r  r  r  r  
safe_ordersafe_string_nsafe_symbolr  r  )r  orderr  r  r   feeCurrencyIdrN  responseStopr
  rO  rP  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           	      b    d|i}|                      ||||                     ||                    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  )fetch_my_tradesrR  )r  r/   r  r  r  r  rS  s          r  fetch_order_tradeszkucoin.fetch_order_trades}
  s:     r
 ##FE5$++gv:V:VWWWr  c                    |                                   d}|                     |dd          \  }}|r|                     d||||          S i }|                     |dd          }|r|t	          | j        dz             d}| |                     |          }|d         |d<   |||d	<   | j        d
         }	d}
d}|                     d||          \  }}|r*| 	                    | 
                    ||                    }n|	dk    r1|||d<   |                     | 
                    ||                    }nI|	dk    r,d}
|                     | 
                    ||                    }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>`
        Frr   r  r  Nz: fetchMyTrades() requires a symbol parameter for hf ordersr/   r  r1  r  r  r  r  private_get_limit_fillsTz% fetchMyTradesMethod() invalid methodr  r2  )rM  r  r=  r  r   r/   r  r  handle_until_optionprivateGetHfFillsrR  privateGetFillsprivateGetLimitFillsr   r  r  parse_trades)r  r  r  r  r  r  rS  r  r  methodparseResponseDatar  r  r]  s                 r  rf  zkucoin.fetch_my_trades
  s    	88R\]]& 	d44_feUZ\bccc^^FD%00 	l&.#DG.j$jkkk[[((F &tGH"'GJ34!227GVLL 	S--dkk'6.J.JKKHH*** %*	"++DKK,H,HIIHH000 !%00Wf1M1MNNHH*Q QRRRR ~~h33 	7FF^^D'266F  >>>r  c                    |                                   |                     |          }d|d         i}|                     |                     ||                    }|                     |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>`
        r  r/   r  )rM  r  publicGetMarketHistoriesrR  r  rn  )	r  r  r  r  r  r  rS  r  r]  s	            r  fetch_tradeszkucoin.fetch_trades
  s     	V$$fTl
 00Wf1M1MNN &"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  	liquidityro  i@B rL  	dealValuer  r  	dealPricer  r  r  r*  rM  ry  r  r  feeRate)r  r  rater  matchr  )r  r/   ra  r   rp  r  r  takerOrMakerr  r  r  r  r*  )r  r  r`  r  r  r  
safe_trader  )r  r  r  r  r/   r  r|  r   priceStringr  r  r*  feeCostStringrb  rM  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                    |                                   |                     |          }d|d         i}|                     |                     ||                    }|                     |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>`
        r   r/   r  r   r  r  r  T)r  r  r  r  r  r  )	rM  r  privateGetTradeFeesrR  r  r  r  r`  r  )	r  r  r  r  rS  r  r  firstr  s	            r  fetch_trading_feezkucoin.fetch_trading_fee  s     	V$$vd|
 ++DKK,H,HII ~~h33tQ''##E844&&x88%%e^<<%%e^<<
 
 	
r  c                 V   |                      ||          \  }}|                                  |                     |           |                     |          }|d         ||d}|||d<   d}|                     |          \  }}|*|                     |                                          |d<   d}	|                     |ddd          \  }	}|	rd	|d
<   |                     | 	                    ||                    }
| 
                    |
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>`
        r/   )r  r  r  Nr  r  r   r  FINTERNALfeeDeductTyper  )handle_withdraw_tag_and_paramsrM  r  r  rN  rO  rP  r  privatePostWithdrawalsrR  r  parse_transaction)r  r)  r  r  r  r  r  rS  r?  r  r  r  s               r  r   zkucoin.withdraw  sH    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$..t{{7F/K/KLL ~~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  rz  r  rL  createAt	updatedAtr  isInnerr  r  r/   withdrawalIdr   rp  r  r  	addressToaddressFromr  tagTotagFromtxidr  r:   remark)internalr*  r  )r  r  r  r  r+   
string_divr  r  r  r  r`  r  r2  r  )r  transactionr  rI  r)  r  r  r  	txidPartsnumTxidPartsr  	rawStatusr*  feeCostrz  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                 v   |                                   d}|                     |dd          \  }}|r|                     d||||          S i }d}| |                     |          }|d         |d<   |||d<   |                     d||          \  }}d}|K|d	k     rE|                     |d
z            |d<   |                     |                     ||                    }n0|||d<   |                     |                     ||                    }|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>`
        Fr`   r  Nr/   r  r1  r      |{r  r  r  r2  r  r  )
rM  r  r=  r  rj  r  privateGetHistDepositsrR  privateGetDepositsparse_transactions
r  r)  r  r  r  r  rS  r  r  r9  s
             r  fetch_depositszkucoin.fetch_deposits[  sr    	88R\]]& 	b44_dESXZ`aaa}}T**H"*4.GJ"'GJ227GVLL!6!6!%!2!254<!@!@GI224;;w3O3OPPHH %*	"..t{{7F/K/KLLHN  '0&&|XuefV_M`aaar  c                 v   |                                   d}|                     |dd          \  }}|r|                     d||||          S i }d}| |                     |          }|d         |d<   |||d<   |                     d||          \  }}d}|K|d	k     rE|                     |d
z            |d<   |                     |                     ||                    }n0|||d<   |                     |                     ||                    }|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>`
        Fr   r  Nr/   r  r1  r  r  r  r  r  r2  r  r  )
rM  r  r=  r  rj  r  privateGetHistWithdrawalsrR  privateGetWithdrawalsr  r  s
             r  fetch_withdrawalszkucoin.fetch_withdrawals  st    	88ASU_``& 	e445GuV[]cddd}}T**H"*4.GJ"'GJ227GVLL!6!6!%!2!254<!@!@GI55dkk'66R6RSSHH %*	"11$++gv2N2NOOHP  '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)rG  r`  r  r+   
string_add)r  r:  rG  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                 	   |                                   |                     |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    }|r7||d         |d<   | 	                    | 
                    ||
                    }ng|r*|                     | 
                    ||
                    }n;||d         |d<   ||d<   |                     | 
                    ||
                    }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>`
        r)  NrV   r^  r>   r  r  r  Fr  r  r  r?   r/   balanceCurrencyr  )r  r   rp  r  assetsr   r  _	baseAsset
quoteAssetr   balancer  r  r  holdsr  )rM  r  r  r`  r  r  rd  r  r  privateGetIsolatedAccountsrR  privateGetMarginAccountrF  r  r  r  r`  r  r  safe_balancer  rG  )#r  r  r)  r  r^  rf  r  r  r  r  r*  r  rS  r  r  r  r  r  r  r:  r  r  r  r  baseCode	quoteCode	subResultr   r  rI  	codeInnerbalanceType
codeInner2rG  
returnTypes#                                      r  fetch_balancezkucoin.fetch_balance  s    	//}}T**H((~}V\]]((EE6FGG}MM66**~~fdE22 	D64(( >>~vVV
E*,E$*2Dw&=DH,< 
	L#-5d^)*66t{{7E7R7RSSHH 	L33DKK4O4OPPHH#&.tn
#"GFO..t{{7E/J/JKKH\ 
 

  #	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                    |                                   |                     |          }|                     ||          }|                     |          }|                     |          }	|                     || j                  }
|                     |	| j                  }|dk    r|	dk    rt          | j        dz             |d         |d}d|vr|                                 |d<   | 	                    | 
                    ||                    }|                     |d          }|                     ||          S |d         |d}|
s|rD|                     || j                  r||d<   d	}|                     |	| j                  r|	|d
<   d	}	||d<   |	|d<   d|vr|                                 |d<   |                     | 
                    ||                    }|                     |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>`
        r  r  zK transfer() only supports transferring from futures account to main accountr/   )r  r  bizNor  fromTagr  toTagfromtor  )rM  r  currency_to_precisionconvert_type_to_accountin_arrayidsr   r/   uuid22futuresPrivatePostTransferOutrR  r  parse_transferr   privatePostAccountsInnerTransfer)r  r)  r  r  r  r  r  requestedAmountfromIdtoIdfromIsolated
toIsolatedrS  r  r  s                  r  r   zkucoin.transfer  s*    	==&&44T6BB--k::++I66}}VTX66]]422
Zv~~#DG.{${|||$TN) G v%%#';;== 99$++gv:V:VWWH2 >>(F33D&&tX666 %TN) G  &z &==22 ()/GI&'F==tx00 &'+GG$%D$GFO GDM6))'+yy{{$<<T[[RX=Y=YZZH >>(F33D&&tX666r  c           
      N   |                      |d          }|                     |d          }|                     |d          }|                     |d          }|                     |d          }|                     | j        d          }|                     |||          }	|                     |||          }
|                     |dd          |                     ||          ||                     |          |                     |d	          |	|
| 	                    |          |d
	S )NrL  r  r   payAccountTyperecAccountTyper  applyIdr  r  )	r/   r  r   rp  r  r  r  r   r  )
r  r  safe_string_lowerr  r  r`  r  r  r  parse_transfer_status)r  r   r  r   rI  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 Cryptory  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_type4  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	directionrL  accountTypecontextr  r  ru  r*  rw  )r  r  )r/   r  rG  referenceIdreferenceAccountr  r  r  r   rp  beforeafterr   r*  r  )
r  r  r  r  r  r  jsonloads	Exceptionr  )r  itemr  r/   rI  r)  r  balanceAfterr  r  r  r   rp  rG  r  r	  r  r  ru  excr*  r  rM  s                          r  parse_ledger_entryzkucoin.parse_ledger_entry`  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                    |                                   |                                  d}|                     |dd          \  }}|                     |d          }|                     |d          }|r|                     d||||          S i }|||d<   d}| |                     |          }|d         |d<   |                     d	||          \  }}d}	|                     d|          \  }	}d}
|rV|	*| 	                    | 
                    ||                    }
nS|                     | 
                    ||                    }
n)|                     | 
                    ||                    }
|                     |
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>`
        Frk   r  r  Nr  r/   r  r  r  r2  )rM  load_accountsr  r  rd  r=  r  rj  r   privateGetHfMarginAccountLedgersrR  privateGetHfAccountsLedgersprivateGetAccountsLedgersr  parse_ledgerr  )r  r)  r  r  r  r  r  rS  r  r  r  dataListr  r2  s                 r  fetch_ledgerzkucoin.fetch_ledger  s	    	88PZ[[&~~fd++64(( 	`44]D%QVX^___
 !&GI}}T**H"*4.GJ227GVLL
!??vVV
F 	T%@@WV\A]A]^^;;DKKQW<X<XYY55dkk'66R6RSSHL >>(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   ro  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 )
NrL  r   r      r  dailyIntRatedayRatioi \&)r  rz  periodr   rp  r  )r`  r  r  r  r[  r  )r  r  r  timestampIdr   rI  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                 (   |                                   d}|                     d|          \  }}|d}i }d}| |                     |          }	|	d         |d<   |dk    r*|                     |                     ||                    }n)|                     |                     ||                    }|                     |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   )	rM  r  r  r  rR  privateGetMarginAccountsr  r  parse_borrow_interests)r  r)  r  r  r  r  r  rS  r  r  r  r  s               r  fetch_borrow_interestzkucoin.fetch_borrow_interest?  s(    	
!??@UW]^^
F J}}T**H'/~GO$##66t{{7F7S7STTHH44T[[&5Q5QRRHB ~~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  rL  r  r  r  r  accruedInterestr,  )	r  r  r  r  interestRateamountBorrowedr   rp  r  )r  r  r  r  r  r  r  )r  r  r  r  r  r  r   isolatedBaser8  r  rI  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                    |                                   |                     d|          }|                     |dd          }|dk    }d|i}|||d<   |                     d||          \  }}|||d	<   |                     |                     ||                    }	|                     |	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
        rX   r   r  r  
isIsolatedN	startTimeendTimer1  r  r2  )	rM  r  r  rj  privateGetMarginInterestrR  r  r  parse_borrow_rate_histories)r  codesr  r  r  r  r  r<  rS  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00Wf1M1MNN* ~~h//~~dG,,//eUEJJJr  c                    |                                   |                     d|          }|                     |dd          }|dk    }|                     |          }||d         d}	|||	d<   |                     d	|	|          \  }	}|||	d
<   |                     |                     |	|                    }
|                     |
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>`
        rX   r   r  r  r/   )r<  r  Nr=  r>  r1  r  r2  )
rM  r  r  r  rj  r?  rR  r  r  r)  )r  r)  r  r  r  r  r  r<  r  rS  r  r  rB  s                r  fetch_borrow_rate_historyz kucoin.fetch_borrow_rate_history  s    	99:TV\]]%%lAw??
 J.
==&&$ 
 
 #(GK 229gvNN"'GJ00Wf1M1MNN* ~~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  ra  rb  r&  )r  r  rA  r  r  borrowRateHistoriesr  r  r)  borrowRateStructurerb  s              r  r@  z"kucoin.parse_borrow_rate_historiesL  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                 @   |                                   |                     |          }|d         |                     ||          dd}|                     |                     ||                    }|                     |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>`
        r/   FOK)r  r  rW  r  )rM  r  r  privatePostMarginBorrowrR  r  parse_margin_loanr  r)  r  r  r  rS  r  r  s           r  borrow_cross_marginzkucoin.borrow_cross_marginf  s     	==&& ..tV<< 
 

 //GV0L0LMM ~~h33%%dH555r  c                 z   |                                   |                     |          }|                     |          }|d         |                     ||          |d         ddd}|                     |                     ||                    }|                     |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>`
        r/   rJ  T)r  r  r  rW  r<  r  )rM  r  r  r  rK  rR  r  rL  
r  r  r)  r  r  r  r  rS  r  r  s
             r  borrow_isolated_marginzkucoin.borrow_isolated_margin  s     	V$$==&& ..tV<<Tl 
 
 //GV0L0LMM ~~h33%%dH555r  c                 >   |                                   |                     |          }|d         |                     ||          d}|                     |                     ||                    }|                     |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>`
        r/   )r  r  r  )rM  r  r  privatePostMarginRepayrR  r  rL  rM  s           r  repay_cross_marginzkucoin.repay_cross_margin  s     	==&& ..tV<<
 
 ..t{{7F/K/KLL ~~h33%%dH555r  c                 x   |                                   |                     |          }|                     |          }|d         |                     ||          |d         dd}|                     |                     ||                    }|                     |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>`
        r/   T)r  r  r  r<  r  )rM  r  r  r  rS  rR  r  rL  rP  s
             r  repay_isolated_marginzkucoin.repay_isolated_margin  s     	V$$==&& ..tV<<Tl	
 
 ..t{{7F/K/KLL ~~h33%%dH555r  c                    |                                  }|                     |d          }|                     |d          |                     ||          |                     |d          d ||                     |          |dS )Nr  orderNo
actualSize)r/   r  r  r  r   rp  r  )r  r  r  r  r  )r  r  r  r   rI  s        r  rL  zkucoin.parse_margin_loan  s     %%''	%%dJ77
""433//
HEE&&t\::"Y//
 
 	
r  rA  c                     |                                   |                     |          }|                     |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>`
        r  r  )rM  r.  r  parse_deposit_withdraw_fees)r  rA  r  r  r  s        r  fetch_deposit_withdraw_feesz"kucoin.fetch_deposit_withdraw_fees  sX     	++F33& ~~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-TIMESTAMPr_  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  ro  bodyheaders)r  r  r  rd  implode_paramsextract_paramsr   is_empty	rawencoder  r  strr  rR  r   hmacencoder   r   hashlibsha256r  r`  )r  r  r   ro  r  rb  ra  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  r`  r/   throw_exactly_matched_exceptionr   )r  r)  reasonr  ro  rb  ra  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   rD  r   rJ  rg  rU  rY  r   rW  rg  r   r  r   r   r  r  ra  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   r?  rA  rJ  r  rg  rf  r   rs  r  r   r  r   r  r   r  r  r  r  r   r  r   r   r  r  r  r  r  r"  r)  r$  r4  r:  rC  rE  r@  rN  rQ  rT  rV  rL  r\  rz  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Z V V V Vp %' . .4= . . . .` 79 
 
# 
 
 
 
6 <> &? &?s &? &? &? &?P* * * * * *XP P P"X X6 XV X X X Xt 04B 1G 1GW 1G7 1G 1G 1G 1Gf 02 %; %;3 %;f %; %; %; %;N
 
 
4 
 
 
 
* 26DW[df 2H 2H# 2Hc 2HQT 2Hkoptku 2H 2H 2H 2Hh 8: : :3 : : : :2 79 : :# : : : :@
 
h 
 
 
 
& DF $0 $0s $0 $0 $0 $0L :>b ? ?s ?3 ?Y ? ? ? ?B> > > gksu M. M.3 M.i M.y M.RW M.`c M. M. M. M.^ _a M MC My MPU M M M M RT 
O 
O 
O5 
O 
O 
O 
O SU 
P 
P 
PE 
P 
P 
P 
P @B J' J'D$6 J' J' J' J'Xs     os{} 7, 7,3 7,i 7,y 7,Z_ 7,hk 7, 7, 7, 7,r `drv  @B &. &.S &.# &.Y &.i &.Y\ &.lo &. &. &. &.P 37r , ,s ,C , , , ,\ /32 % % % % % %N <@daenp j? j?S j? j?[^ j? j? j? j?X 154VZce Q Q# QS QPS Qjnotju Q Q Q Q6 /3TXac S S S3 Sc Shlmrhs S S S S< 26b 96 96c 963 96 96 96 96vm m m5 m m m m^ 9=4^bkm X XS X# XS XX[ X X X X" -1tRV_a _? _?c _? _?C _? _? _? _?B 6:UW &? &?3 &?s &?# &?\`af\g &? &? &? &?P{ { {5 { { { {z 57 $
 $
 $
;N $
 $
 $
 $
L ?C2 .6 .6S .6% .6 .6 .6 .6`: : :f
 f
x f
; f
 f
 f
 f
P *.Dt\^ Jb Jb3 Jbc Jb Jbcghsct Jb Jb Jb JbX -1tRV_a Ke Kec Ke KeC Kefjkvfw Ke Ke Ke KeZ   $& b b( b b b bH [] S7 S7S S7% S7c S7c S7an S7 S7 S7 S7j5
 5
 5
 5
 5
 5
n: : :*3 *3 *3XL
 L
 L
 L
 L
 L
\ (,$TZ\ Z@ Z@ Z@C Z@s Z@ Z@ Z@ Z@x MO 2 2 2 2O O O
 
 
 
 
 
< 15DW[jnwy ]9 ]9# ]9c ]9QT ]9dg ]9 ]9 ]9 ]9~H
 H
& H
 H
 H
 H
T 154VZce /K /KS /KPS /K /K /K /Kb AESW`b 1H 1Hc 1H# 1HS 1H 1H 1H 1Hf# # #4 DF 6 6 6U 6 6 6 6B TV #6 #6S #6 #6U #6 #6 #6 #6J <> 6 6s 6 6 6 6> LN !6 !6C !6s !6 !6 !6 !6F
 
 
 
 
 
& <@ I I I I I I> &eBSW <P <P <P <P|      r  r-   )4ccxt.base.exchanger   ccxt.abstract.kucoinr   rj  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   ( ' ' ' ' ' , , , , , ,    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  