
    i                    @   d dl mZ d dlmZ d dlmZmZmZmZm	Z	m
Z
mZmZmZmZmZmZ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)  G d dee          Z*dS )    )kucoin)ImplicitAPI)BalancesCurrencyIntMarginModificationMarketNumOrder	OrderBookOrderRequest	OrderSide	OrderTypeStrStringsTickerTickersTradeTransactionTransferEntry)List)AuthenticationError)PermissionDenied)AccountSuspended)ArgumentsRequired)
BadRequest)InsufficientFunds)InvalidOrder)OrderNotFound)NotSupported)RateLimitExceeded)ExchangeNotAvailable)InvalidNonce)	TICK_SIZE)Precisec                       e Zd Z fdZi fdZi fdee         fdZi fdZdddi fde	d	e
d
e
dee         fdZd>dedefdZi fde	fdZdi fde	d
e
defdZi fde	defdZdi fdedefdZd>dedefdZdddi fded	e
d
e
fdZi fde	fdZdi fdefdZd>defdZdi fde	dedededef
dZ i fdee!         fdZ"di fde	dedededef
d Z#di fd!e	defd"Z$di f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
fd&Z)dddi fded	e
d
e
dee*         fd'Z+dddi fded	e
d
e
dee*         fd(Z,ddi fd!edefd)Z-d>dede*fd*Z.i fde	fd+Z/de0fd,Z1i fde0fd-Z2i fde	ded.e	d/e	de3f
d0Z4d>d1e5fd2Z6d3 Z7dddi fded	e
d
e
fd4Z8ddi fde	d	e
d
e
dee9         fd5Z:d>dede9fd6Z;dddi fded	e
d
e
dee<         fd7Z=dddi fded	e
d
e
dee<         fd8Z>i fde	fd9Z?d>defd:Z@dddi fded	e
d
e
fd;ZAd>defd<ZBdi fde	dede*fd=ZC xZDS )?kucoinfuturesc                    |                      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 dWdXdYdZgd[d\d]d]d^d^d_d`dadbddddcddi dedfdgdfdhdfdidfdjdkdldfdmdfdndfdodfdpdfdqdfdrdfdsdfdtdfdudfdvdfdwdfdxdfidydfidzi d{dkd|d}d~dfddfddfddfddfddkddfddfddfddfdd}dd}ddfddfdd}d}dfdfddfdfdfdkdkdfdfdfdfdfdfddfdfdfd}dfdfdfdddddfiiddt          di dt
          dt          dt          dt          dt          dt
          dt          dt          dt          dt          dt
          dt          dt          dt          dt          dt          dt          t          t          t          t          t          t          t          t          t
          t          t          ddt          idddd|                     d          |                     d          |                     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|                     d          |                     d          g|                     d          |                     d          g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|                     d          |                     dŦ          g|                     d          |                     dƦ          ggdǜdȜddi i dɜdʜddddddddҜdfd ddddddd dddddݜd
dddi i dddiiddodiiddddddd          S )Nidr'   namezKuCoin Futures	countriesSC	rateLimitK   versionv1	certifiedTprocommentzPlatform 2.0quoteJsonNumbersFhasCORSspotmarginswapfutureoption	addMargincancelAllOrderscancelOrdercloseAllPositionsclosePositionclosePositionscreateDepositAddresscreateOrdercreateOrderscreateReduceOnlyOrdercreateStopLimitOrdercreateStopLossOrdercreateStopMarketOrdercreateStopOrdercreateTakeProfitOrdercreateTriggerOrderfetchAccountsfetchBalancefetchBorrowRateHistoriesfetchBorrowRateHistoryfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositAddressfetchDepositsfetchDepositWithdrawFeefetchDepositWithdrawFeesfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchL3OrderBookfetchLedgerfetchLeverageTiersfetchMarginAdjustmentHistoryfetchMarginModefetchMarketLeverageTiersfetchMarketsfetchMarkOHLCVfetchMyTrades
fetchOHLCVfetchOpenOrders
fetchOrderfetchOrderBookfetchPositionfetchPositionModefetchPositionsfetchPremiumIndexOHLCVfetchStatusfetchTickerfetchTickers	fetchTimefetchTradesfetchTransactionFeefetchWithdrawalssetLeveragesetMarginModetransferwithdrawurlszdhttps://user-images.githubusercontent.com/1294454/147508995-9e35030a-d046-43a1-a006-6fabd981b554.jpgzhttps://docs.kucoin.com/futureszhttps://docs.kucoin.comzhttps://futures.kucoin.com/z(https://futures.kucoin.com/?rcode=E5wkqezhttps://openapi-v2.kucoin.comzhttps://api-futures.kucoin.comz)https://futures.kucoin.com/_api/web-front)publicprivatefuturesPrivatefuturesPublicwebExchange)logodocwwwreferralapirequiredCredentials)apiKeysecretpasswordr   zcontracts/active   zcontracts/{symbol}zcontracts/risk-limit/{symbol}tickerzlevel2/snapshotgHzG?zlevel2/depth{limit}zlevel2/message/queryzlevel3/message/queryzlevel3/snapshotztrade/historyzinterest/queryzindex/queryzmark-price/{symbol}/currentzpremium/queryzfunding-rate/{symbol}/current	timestampstatuszkline/queryzbullet-public)getpostzaccount-overviewztransaction-historyg(\@zdeposit-addresszdeposit-listzwithdrawals/quotaszwithdrawal-listztransfer-listorders
stopOrdersrecentDoneOrdersorders/{orderId}zorders/byClientOidfillsrecentFillsopenOrderStatisticsposition	positions)zfunding-historysub/api-keyztrade-statistics)withdrawalstransfer-outztransfer-inr   zorders/testz#position/margin/auto-deposit-statuszposition/margin/deposit-marginz position/risk-limit-level/changezbullet-privater   zsub/api-key/update)zwithdrawals/{withdrawalId}zcancel/transfer-outr   r   r   r   zorders/client-order/{clientOid})r   r   deleter   zcontract/{symbol}/funding-rates)r~   r}   r   precisionMode
exceptions400401403404405415429500503100001100004101030200004230003260100300003300012)400001400002400003400004400005400006400007404000400100411100500000zPosition does not exist)exactbroadfeesz0.0006z0.0002050200z0.00051000z0.000420004000z0.000388000z0.0003515000z0.0003225000z0.0003400006000080000z0.02z0.015z0.01z-0.003z-0.006z-0.009z-0.012z-0.015)takermaker)	tierBased
percentager   r   tiers)r   r   ry   deposit)tradingfundingcommonCurrenciesHOTNOWDADIWAXPTriasVAIOTBTC)HOTEDGEWAXTRYVAIXBT         <   x      i  i  i  i`'  )1m3m5m15m30m1h2h4h6h8h12h1d1w-USDTPOSTr   v2GET)r}   r~   omniethtrx)OMNIERC20TRC20)r/   symbolSeparatordefaultTypecodemarginModesmarginTypesversionsnetworks)
timeframesoptions)deep_extendsuperr'   describer$   r   r   r    r!   r"   r   r   r   r#   r   r   parse_number)self	__class__s    X/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/kucoinfutures.pyr  zkucoinfutures.describe   s   mT : : C C E E zH
/zH
$zH
 $zH
 	zH

 tzH
 zH
 4zH
 ~zH
 zH
  EEE %E 	E
 $E %E TE "4E tE $UE  E !%E 'E tE E  (!E" '#E E$ &t%E& ('E( "4)E* (+E, %d-E.  /E0 1E2 +E3E4 )%5E6 $T7E8 '9E: (;E< "5=E> &t?E@  AEB *5CED +EEE E EF &tGEH #DIEJ *4KEL "5MEN *5OEP +EQER #DSET tUEV %eWEX /YEZ "5[E\ +D]E^ _E` !%aEb  cEd deEf "4gE E Eh diEj !$kEl  mEn $UoEp !$qEr )%sEt tuEv twEx yEz T{E| t}E~ &uE@ #DAEB uCED  EEF DGEH DIE EzH
` ~5- 5F=>&F%E#N  azH
@ " $ $AzH
J *A,a 8 !!	
 *4 .q / / *1 ( )! &q 6q ( 8  $Q!" !!#$ &q% * (+" "4*D-t *1 '	
 -a *1 ( !$ %a +A +A -a   &t .q  #A!" $T#$ ,0'(,-)  . ()()'("&'+?@:;<=*+'(./  78/0,-"&&''(;< I-# -#^ 91 QM MKzH
f YgzH
h :. < <	
 < : , / / l j . / / /  /!" l#$ 2*11111*(.29  > .}?" "izH
n !%"&!..x88!..x88 "..s33T5F5Fx5P5PQ!..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(8S8ST!..v668I8I)8T8TU!..v668I8I)8T8TU!..w779J9J99U9UV!..w779J9J89T9TU!..w779J9J89T9TU!..w779J9J89T9TU!..w779J9J89T9TU"  "..s33T5F5Fv5N5NO!..t44d6G6G6P6PQ!..u55t7H7H7P7PQ!..u55t7H7H7P7PQ!..v668I8I&8Q8QR!..v668I8I#8N8NO!..v668I8I#8N8NO!..v668I8I#8N8NO!..w779J9J89T9TU!..w779J9J89T9TU!..w779J9J89T9TU!..w779J9J89T9TU!..w779J9J89T9TU"! % %N "'"' "!	 O- -ozH
J ! !KzH
\     #&%!! *D!' -t &  #"" ) yzH
 zH
 zH
 z z z	    c                     |                      |          }|                     |di           }|                     |d          }|dk    rdndddd|dS )am  
        the latest known information on the availability of the exchange API
        :see: https://www.kucoin.com/docs/rest/futures-trading/market-data/get-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>`
        datar   openokmaintenanceN)r   updatedetaurlinfo)futuresPublicGetStatus
safe_valuesafe_string)r	  paramsresponser  r   s        r  fetch_statuszkucoinfutures.fetch_statusY  so     ..v66 x44!!$11%//ddm
 
 	
r  returnc                 ,   |                      |          }g }|                     |dg           }t          dt          |                    D ]F}||         }|                     |d          }|                     |d          }|rdnd}	|	 }
|                     |d          }|                     |d          }|                     |d	          }|                     |          }|                     |          }|                     |          }|d
z   |z   dz   |z   }d}|	r|dz   |                     |d          z   }d}|                     |d          }|                     |d          }|                     |d          }|                     |d          }|                     |d          }|}||                     |d          }|                     |d          }||                     |d          }|                     |d          }|T|                     |d          }|                     |d          }| 	                    t          j        ||                    }|                    i d|d|d|d|d|d|d |d!|d"|d#dd$dd|
d|	d%dd&|d'k    d(dd)| ||                     |d*          |                     |d+          | 	                    t          j        |                    ||                     |          dd||d,| 	                    d-          |                     |d.          d/||d/||d/|                     |d0          |                     |d          d/d1|                     |d2          |d3           H|S )4a8  
        retrieves data on all markets for kucoinfutures
        :see: https://www.kucoin.com/docs/rest/futures-trading/market-data/get-symbols-list
        :param dict [params]: extra parameters specific to the exchange api endpoint
        :returns dict[]: an array of objects representing market data
        r  r   symbol
expireDateTFbaseCurrencyquoteCurrencysettleCurrency/:r9   r    r:   	isInverser   
multipliertickSizelotSizeNbaseMinSizemaxOrderQtybaseMaxSizemaxPricequoteMaxSizer)   basequotesettlebaseIdquoteIdsettleIdtyper7   r8   r;   activeOpencontractlineartakerFeeRatemakerFeeRate)amountprice1maxLeverage)minmaxquoteMinSize)leverager<  r=  costfirstOpenDate)inverser   r   contractSizeexpiryexpiryDatetimestrike
optionType	precisionlimitscreatedr  )futuresPublicGetContractsActiver  rangelenr  safe_integersafe_currency_codeyymmddsafe_numberr  r%   
string_divappend
string_absiso8601)r	  r  r  resultr  imarketr)   rH  r:   r9   r2  r3  r4  r/  r0  r1  r  r5  rF  r   r'  r(  r)  limitAmountMinlimitAmountMaxlimitPriceMaxbaseMinSizeStringquoteMaxSizeStrings                                r  fetch_marketszkucoinfutures.fetch_marketst  s    77??~ x44q#d))$$ S	 S	A!WF!!&(33B&&v|<<F#.TTF:D%%fn==F&&v??G''0@AAH**622D++G44E,,X66FCZ%'#-6FD  #FB(?(??oofk::G%%fh77F))&,??J''
;;H&&vy99G$N%!%!1!1&-!H!H!--fmDDN%!%!1!1&-!H!H ,,VZ@@M$$($4$4V]$K$K!%)%5%5fn%M%M" $ 1 1'2DEWYj2k2k l lMM 2b2&2 2 	2
 &2 &2 72 H2 2 2 %2 2 &2 %2 6V+2  D!2" g+#2$ #))&.AA))&.AA $ 1 1'2DZ2P2P Q Q "&,,v"6"6"%%   $0055#//FF! !
  .- 
  (, 
  $//GG#//GG  $  ,,V_EEc2 2 2 2 2 2 2f r  c                 X    |                      |          }|                     |d          S )am  
        fetches the current integer timestamp in milliseconds from the exchange server
        :see: https://www.kucoin.com/docs/rest/futures-trading/market-data/get-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
        r  )futuresPublicGetTimestamprR  )r	  r  r  s      r  
fetch_timezkucoinfutures.fetch_time  s/     11&99   6222r  r   Nr  sincelimitc           	         |                                   d}|                     |dd          \  }}|r|                     d|||||d          S |                     |          }|d         }|                     | j        |          }	d|i}
|	|	|
d<   n||
d<   |                     |          d	z  }|                                 }|=||
d
<   ||                     | j        dd          }| 	                    |||z            }n||||z  z
  }||
d
<   ||
d<   | 
                    |                     |
|                    }|                     |dg           }|                     |||||          S )a  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :see: https://www.kucoin.com/docs/rest/futures-trading/market-data/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
        Frg   paginate   r)   r  Ngranularity  fromfetchOHLCVLimittor  )load_marketshandle_option_and_params"fetch_paginated_call_deterministicr\  rR  r  parse_timeframemillisecondsr  sumfuturesPublicGetKlineQueryextend	safe_listparse_ohlcvs)r	  r  	timeframerf  rg  r  ri  r\  marketIdparsedTimeframerequestdurationendAtr  r  s                  r  fetch_ohlcvzkucoinfutures.fetch_ohlcv"  s    	88zZZ& 	w::<QVX]_hjpruvvvV$$$<++DOYGGh
 &%4GM""%.GM"''	22T9!!###GFO}))$,8I3OOHHUEH$455EEEH,,E#GFO224;;w3O3OPP ~~h33  vy%GGGr  r\  c           	         |                      |d          |                     |d          |                     |d          |                     |d          |                     |d          |                     |d          gS )Nr   r            r   )rR  rU  )r	  ohlcvr\  s      r  parse_ohlcvzkucoinfutures.parse_ohlcvV  s     eQ''UA&&UA&&UA&&UA&&UA&&
 	
r  r   c                    |                                   |                     |          }|d         }d|i}|                     |                     ||                    }|                     |di           }|                     |d          }|dk    r|                     |           ||||                     |d          |                     |d          dS )	a  
        fetch the deposit address for a currency associated with self account
        :see: https://www.kucoin.com/docs/rest/funding/deposit/get-deposit-address
        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        r)   currencyr  addressNIMmemochain)r  r  r  tagnetwork)rp  r  futuresPrivateGetDepositAddressrw  r  r  check_address)	r	  r   r  r  
currencyIdr}  r  r  r  s	            r  fetch_deposit_addressz#kucoinfutures.fetch_deposit_addressk  s     	==&&d^


 77GV8T8TUU x44""433w'''"##D&11''g66
 
 	
r  c           	         |                                   |                     |d          }|dk    r|t          | j        dz             |                     |          }d|d         i}|)|dk    s|dk    r||d	<   nt          | j        d
z             d|d	<   |                     |                     ||                    }|                     |di           }|                     | 	                    |d          dz            }	| 
                    ||d         |	dddd          }
| 	                    |d          |
d<   |
S )aZ  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :see: https://www.kucoin.com/docs/rest/futures-trading/market-data/get-part-order-book-level-2
        :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  Nz) fetchOrderBook() can only return level 2r  r)      d   rg  z2 fetchOrderBook() limit argument must be 20 or 100r  ts@B bidsasksr   r   sequencenonce)rp  rU  r   r)   r\   futuresPublicGetLevel2DepthLimitrw  r  parse_to_intrR  parse_order_book)r	  r  rg  r  r  r\  r}  r  r  r   	orderbooks              r  fetch_order_bookzkucoinfutures.fetch_order_book  s]    	  11A::%+TW'RRSSSV$$fTl
 ##(   +_!_```!GG88Wf9U9UVV& x44%%d&7&7d&C&Cg&MNN	))$x0@)VU[]^`abb	!..tZ@@	'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://www.kucoin.com/docs/rest/futures-trading/market-data/get-ticker
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        r  r)   r  )rp  r\  futuresPublicGetTickerrw  parse_ticker)r	  r  r  r\  r}  r  s         r  fetch_tickerzkucoinfutures.fetch_ticker  sw     	V$$fTl
 ..t{{7F/K/KLL&   &!16:::r  symbolsc                    |                                   |                     |          }|                     |          }|                     |dg           }|                     ||          }|                     |d|          S )a*  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
        :see: https://www.kucoin.com/docs/rest/futures-trading/market-data/get-symbols-list
        :param str[] [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  )rp  market_symbolsrO  rx  parse_tickersfilter_by_array_tickers)r	  r  r  r  r  tickerss         r  fetch_tickerszkucoinfutures.fetch_tickers  s     	%%g..77??~ ~~h33$$T733++GXwGGGr  c                    |                      |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!|          S )"Nr  r   r=  lastTradePricer  gư>r   datetimehigh	highPricelowlowPricebidbestBidPrice	bidVolumebestBidSizeaskbestAskPrice	askVolumebestAskSizevwapr  closelastpreviousClosechangepriceChgr   priceChgPctaveragevolumeOf24hturnoverOf24h)
baseVolumequoteVolumer  )r  safe_marketsafe_string_2safe_integer_productsafe_tickerrY  )r	  r   r\  r{  r  r   s         r  r  zkucoinfutures.parse_ticker0  s   ^ ##FH55!!(FC88!!&'3CDD--fdHEE	 !
fX&!
!
 Y//!
 D$$V[99	!

 4##FJ77!
 4##FN;;!
 ))&-@@!
 4##FN;;!
 ))&-@@!
 D!
 D!
 T!
 D!
 T!
 d&&vz::!
  $**6=AA!!
" t#!
$ **6=AA++FODD)!
 !
 !
* +  	r  c                    |t          | j        dz             |                                  |                     |          }d|d         i}|||d<   |||d<   |                     |                     ||                    }|                     |d          }|                     |dg           }	g }
t          d	t          |	                    D ]}|	|         }| 	                    |d
          }|

                    |||                     |                     |d                    ||                     |          |                     |d          |                     |d          |                     |d          |                     |d          |                     |d          |                     |d          d           |
S )aV  
        fetch the history of funding payments paid and received on self account
        :see: https://www.kucoin.com/docs/rest/futures-trading/funding-fees/get-funding-history
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch funding history for
        :param int [limit]: the maximum number of funding history structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding history structure <https://docs.ccxt.com/#/?id=funding-history-structure>`
        Nz1 fetchFundingHistory() requires a symbol argumentr  r)   startAtmaxCountr  dataListr   	timePointr"  r   fundingRate	markPricepositionQtypositionCost)r  r  r   r   r  r)   r<  r  r  r  r  )r   r)   rp  r\  futuresPrivateGetFundingHistoryrw  r  rP  rQ  rR  rW  rS  r  rY  rU  )r	  r  rf  rg  r  r\  r}  r  r  r  r   r[  listItemr   s                 r  fetch_funding_historyz#kucoinfutures.fetch_funding_history  s    >#DG.a$abbbV$$fTl
 !&GI"'GJ77GV8T8TUU. x00??4R88q#h--(( 	 	A{H))(K@@IKK  //0@0@K[0\0\]]& LL33&&x66**8Y??#//-HH!--hDD#//-HH $ 0 0> J J      r  c                    |                                   |                     |          }d|d         i}|                     |                     ||                    }|                     |di           }|                     ||          S )a  
        :see: https://docs.kucoin.com/futures/#get-position-details
        fetch data on an open position
        :param str symbol: unified market symbol of the market the position is held in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        r  r)   r  )rp  r\  futuresPrivateGetPositionrw  	safe_dictparse_positionr	  r  r  r\  r}  r  r  s          r  fetch_positionzkucoinfutures.fetch_position  s     	V$$fTl
 11$++gv2N2NOOZ ~~h33""4000r  c                     |                                   |                     |          }|                     |d          }|                     ||          S )ak  
        fetch all open positions
        :see: https://docs.kucoin.com/futures/#get-position-list
        :param str[]|None symbols: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        r  )rp  futuresPrivateGetPositionsrx  parse_positions)r	  r  r  r  r  s        r  fetch_positionszkucoinfutures.fetch_positions  sU     	226::^ ~~h//##D'222r  c                    |                      |d          }|                     ||          }|                     |d          }|                      |d          }d }t          j        |d          rd}nt          j        |d          rd}t          j        |                      |d                    }|                      |d          }t          j        ||          }	|                      |d	          }
|                     |d
          }|rdnd}| 	                    i d|d|                      |d          d|                      |d          d|d| 
                    |          dd d|                     |          d|                     |	          d|                     |d          d|                     |d          d|                     |d          d|                     |          d|                     |d          d|                     |
          d|                     t          j        |                    d|                     |d          d |                     |d!          d |                     |d"          |                     |d#          d |                     |d$          ||d d d d%
          S )&Nr  currentTimestamp
currentQtyr   longshortposCostposInitunrealisedPnl	crossModecrossisolatedr  r)   r   r  lastUpdateTimestampinitialMargininitialMarginPercentagemaintenanceMarginposMaintmaintenanceMarginPercentagemaintMarginReq
entryPriceavgEntryPricenotionalrC  realLeverageunrealizedPnl	contractsrG  realizedPnlrealisedPnlliquidationPricer  maintMargin)
marginRatior  r  	lastPrice
collateral
marginModesider   stopLossPricetakeProfitPrice)r  r  rR  r%   	string_gt	string_ltrX  rV  r  safe_positionrY  r  rU  )r	  r   r\  r  r   sizer  r  r  r  r  r  r  s                r  r  zkucoinfutures.parse_positionT  s5   ^ !!(H55!!&&11%%h0BCC	,77T3'' 	DDtS)) 	D%d&6&6x&K&KLL((9==")"4]H"M"M((?CCOOHk::	 )9WWz
!! #
H#
$""8T22#
 d&&vx88#
 	#

 Y//#
 "4#
 T..}==#
 &t'8'89P'Q'Q#
  !1!1(J!G!G#
 *4+;+;HFV+W+W#
 $**8_EE#
 ))(33#
 ((>BB#
 T..}==#
 **7+=d+C+CDD#
  DOOFNCC!#
" 4++HmDD##
$   $ 0 0;M N N))(K@@**8]CC$!#7#
 #
 #
   	r  r5  r  r<  r=  c                    |                                   |                     |          }|                     |dd          }|                     |d          }|                     ||||||          }	d}
|r|                     |	          }
n|                     |	          }
|                     |
di           }|                     ||          S )a2	  
        Create an order on the exchange
        :see: https://docs.kucoin.com/futures/#place-an-order
        :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 a trigger order is triggered at
        :param float [params.stopLossPrice]: price to trigger stop-loss orders
        :param float [params.takeProfitPrice]: price to trigger take-profit orders
        :param bool [params.reduceOnly]: A mark to reduce the position size only. Set to False by default. Need to set the position size when reduceOnly is True.
        :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 float [params.leverage]: Leverage size of the order
        :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.stop]: 'up' or 'down', the direction the stopPrice is triggered from, requires stopPrice. down: Triggers when the price reaches or goes below the stopPrice. up: Triggers when the price reaches or goes above the stopPrice.
        :param str [params.stopPriceType]:  TP, IP or MP, defaults to MP: Mark Price
        :param bool [params.closeOrder]: set to True to close position
        :param bool [params.test]: set to True to use the test order endpoint(does not submit order, use to validate params)
        :param bool [params.forceHold]: A mark to forcely hold the funds for an order, even though it's an order to reduce the position size. This helps the order stay on the order book and not get canceled when the position size changes. Set to False by default.
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        testFNr  )	rp  r\  	safe_boolomitcreate_contract_order_requestfuturesPrivatePostOrdersTestfuturesPrivatePostOrdersr  parse_order)r	  r  r5  r  r<  r=  r  r\  	testOrderorderRequestr  r  s               r  create_orderzkucoinfutures.create_order  s    6 	V$$NN66599	66**99&$fV[]cdd 	C88FFHH44\BBH ~~h33f---r  r   c           	         |                                   g }t          dt          |                    D ]}||         }|                     |d          }|                     |          }|                     |d          }|                     |d          }	|                     |d          }
|                     |d          }|                     |di           }|                     |d         ||	|
||          }|                    |           |                     |          }| 	                    |d	g           }| 
                    |          S )
a  
        create a list of trade orders
        :see: https://www.kucoin.com/docs/rest/futures-trading/orders/place-multiple-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
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r   r  r5  r  r<  r=  r  r)   r  )rp  rP  rQ  r  r\  r  r  rW  futuresPrivatePostOrdersMultirx  parse_orders)r	  r   r  ordersRequestsr[  rawOrderr  r\  r5  r  r<  r=  orderParamsr  r  r  s                   r  create_orderszkucoinfutures.create_orders  sH    	q#f++&& 
	0 
	0AayH%%h99F[[((F##Hf55D##Hf55D__Xx88FOOHg66E//(HbAAK==fTlDRVX^`egrssL!!,////55nEE, ~~h33  &&&r  c                    |                      |          }|                     |dd|                                           }|                     |ddg          }|dk     rt	          | j        dz             t          |                     ||                    }	|||d         ||	dd}
|                     |          \  }}}ddd	d
}| 	                    |dd          }| 	                    |||          }|                     |g d          }|r,|dk    rdnd|
d<   | 
                    ||          |
d<   ||
d<   n]|s|rY|r'|dk    rdnd|
d<   | 
                    ||          |
d<   n&|dk    rdnd|
d<   | 
                    ||          |
d<   d|
d<   ||
d<   |                                }|                     |d          }|dk    r9|t          | j        dz             | 
                    ||          |
d<   |||
d<   d }|                     |dk    d|          \  }}|rd|
d<   |                     |d          }|r|t!          | j        dz             |                     |d          }|r/|                     |d           }|t          | j        d!z             |                     |g d"          }|                     |
|          S )#N	clientOidclientOrderIdr   z1 createOrder() minimum contract order amount is 1r)   )r  r  r  r5  r  rC  MPTPIP)markr  indextriggerPriceTyper!  )r  r  triggerPrice	stopPricebuyupdownstopr%  stopPriceTypeT
reduceOnlytimeInForceLIMITz9 createOrder() requires a price argument for limit ordersr=  r\  FpostOnlyhiddenzW createOrder() does not support the postOnly parameter together with a hidden parametericebergvisibleSizezB createOrder() requires a visibleSize parameter for iceberg orders)r,  r%  r$  r  r  )r\  r  uuidr  r   r)   intamount_to_precisionhandle_trigger_pricesr  price_to_precisionuppersafe_string_upperr   handle_post_onlyr  r   rw  )r	  r  r5  r  r<  r=  r  r\  r  preciseAmountr}  r$  r  r  triggerPriceTypesr#  triggerPriceTypeValueuppercaseTyper,  r.  r/  r0  r1  s                          r  r  z+kucoinfutures.create_contract_order_request  sl   V$$**6;QUQZQZQ\Q\]]6K#ABBA::tw)\\]]]D44VVDDEE&Tl!
 
 8<7Q7QRX7Y7Y4m_
 

  ++F4FOO $ 0 01BDTVf g g6#d#d#dee 	='+u}}dd6GFO#'#:#:6<#P#PGK '<GO$$ 	=o 	= X+/5==$$v'+'>'>v}'U'U$$-1U]]&&'+'>'>v'W'W$$(GL!'<GO$

,,V]CCG##}'2m(mnnn#'#:#:65#I#I &)4&001A5&QQ& 	'"&GJ22 	B+TW  (A  A  B  B  B//&)44 	x//&-@@K"'2v(vwww6#s#s#stt{{7F+++r  r)   c                    |                                   |                     |dd          }|                     |dg          }i }d}|h|t          | j        dz             |                     |          }|d         |d<   ||d<   |                     |                     ||                    }n.||d<   |                     |                     ||                    }| 	                    |d          S )	a  
        cancels an open order
        :see: https://www.kucoin.com/docs/rest/futures-trading/orders/cancel-futures-order-by-orderid
        :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 str [params.clientOrderId]: cancel order by client order id
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r  r  NzJ cancelOrder() requires a symbol argument when cancelling by clientOrderIdr)   r  orderIdr  )
rp  r  r  r   r)   r\  .futuresPrivateDeleteOrdersClientOrderClientOidrw  !futuresPrivateDeleteOrdersOrderIdr  )r	  r)   r  r  r  r}  r  r\  s           r  cancel_orderzkucoinfutures.cancel_orderN  s     	**6;PP6O#455$~'2~(~[[((F &tGH#0GK JJ4;;W^`fKgKghhHH!#GI==dkk'SY>Z>Z[[H x000r  c                    |                                   i }||                     |          |d<   |                     |dd          }|                     |ddg          }d}|r*|                     |                     ||                    }n)|                     |                     ||                    }|                     |d          S )aZ  
        cancel all open orders
        :see: https://www.kucoin.com/docs/rest/futures-trading/orders/cancel-multiple-futures-limit-orders
        :see: https://www.kucoin.com/docs/rest/futures-trading/orders/cancel-multiple-futures-stop-orders
        :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 dict [params.trigger]: When True, all the trigger orders will be cancelled
        :returns: Response from the exchange
        Nr  r)  triggerr  )rp  	market_idsafe_value_2r  futuresPrivateDeleteStopOrdersrw  futuresPrivateDeleteOrdersr  )r	  r  r  r}  r)  r  s         r  cancel_all_orderszkucoinfutures.cancel_all_orderss  s     	 $v 6 6GH  ;;6FI#677 	U::4;;wPV;W;WXXHH66t{{7F7S7STTH x000r  c                    |                                   |                     |          }|                                 }|d         |                     ||          |d}|                     |                     ||                    }|                     |d          }|                     |                     ||          |                     ||          dd          S )a  
        add margin
        :see: https://www.kucoin.com/docs/rest/futures-trading/positions/add-margin-manually
        :param str symbol: unified market symbol
        :param float amount: amount of margin to add
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/#/?id=add-margin-structure>`
        r)   )r  r8   bizNor  in)r<  	direction)rp  r\  r2  r4  -futuresPrivatePostPositionMarginDepositMarginrw  r  parse_margin_modification)	r	  r  r<  r  r\  r2  r}  r  r  s	            r  
add_marginzkucoinfutures.add_margin  s     	V$$yy{{Tl..vv>>
 

 EEdkkRY[aFbFbccd x00{{499$GG..vv>>J
 J
   	r  c                    |                      |d          }|                     ||          }|                      |d          }|                     |d          }|rdnd}|                      |d          }|                     |d          }||                     ||          d |d d |                     |          d ||                     |          d
S )	Nr)   r"  r  r  r  r  r  )
r  r  r5  r  r<  totalr   r   r   r  )r  r  r  rR  safe_symbolrS  rY  )	r	  r  r\  r)   r  r  moder{  r   s	            r  rO  z'kucoinfutures.parse_margin_modification  s    \ dD))!!"f--%%d,<==
OOD+66	#3ww##FH55%%d,>??	&&x88++J77"Y//
 
 	
r  c                 2   |                                   d}|                     |dd          \  }}|r|                     d||||          S |                     |dd          }|                     |dd          }|                     |g d          }|d	k    rd
}n|dk    rd}i }	|s||	d<   n|dk    rt          | j        dz             d}
| |                     |          }
|
d         |	d<   |||	d<   |||	d<   d}|r*| 	                    | 
                    |	|                    }n)|                     | 
                    |	|                    }|                     |di           }|                     |dg           }|                     ||
||          S )a~  
        fetches a list of orders placed on the exchange
        :see: https://docs.kucoin.com/futures/#get-order-list
        :see: https://docs.kucoin.com/futures/#get-untriggered-stop-order-list
        :param str status: 'active' or 'closed', only 'active' is valid for stop orders
        :param str symbol: unified symbol for the market to retrieve orders from
        :param int [since]: timestamp in ms of the earliest order to retrieve
        :param int [limit]: The maximum number of orders to retrieve
        :param dict [params]: exchange specific parameters
        :param bool [params.trigger]: set to True to retrieve untriggered stop orders
        :param int [params.until]: End time in ms
        :param str [params.side]: buy or sell
        :param str [params.type]: limit or market
        :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: An `array of order structures <https://docs.ccxt.com/#/?id=order-structure>`
        FfetchOrdersByStatusri  r)  rD  untiltill)r)  rW  rX  rD  closeddoner  r6  r   z= fetchOrdersByStatus() can only fetch untriggered stop ordersNr)   r  r  r  r  items)rp  rq  fetch_paginated_call_dynamicrF  safe_integer_2r  r   r)   r\  futuresPrivateGetStopOrdersrw  futuresPrivateGetOrdersr  rx  r  )r	  r   r  rf  rg  r  ri  r)  rW  r}  r\  r  responseDatar   s                 r  fetch_orders_by_statusz$kucoinfutures.fetch_orders_by_status  s   " 	88AVXbcc& 	j445JFTY[`bhiii  ;;##FGV<<6#G#G#GHHXFFvF 	h &GHxTW'ffggg[[((F &tGH!&GI$GG 	R77GV8T8TUUHH33DKK4P4PQQHh x<<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/futures/#get-order-list
        :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, or market
        :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>`
        FrP   ri  rZ  rp  rq  r\  ra  r	  r  rf  rg  r  ri  s         r  fetch_closed_ordersz!kucoinfutures.fetch_closed_orders  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 )a\  
        fetches information on multiple open orders made by the user
        :see: https://docs.kucoin.com/futures/#get-order-list
        :see: https://docs.kucoin.com/futures/#get-untriggered-stop-order-list
        :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, or market
        :param boolean [params.trigger]: set to True to retrieve untriggered stop orders
        :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>`
        Frh   ri  r  rc  rd  s         r  fetch_open_orderszkucoinfutures.fetch_open_orders  s~      	88ART^__& 	f445FPUW\^deee**665%PPPr  c                 
   |                                   i }d}|w|                     |dd          }|t          | j        dz             ||d<   |                     |ddg          }|                     |                     ||                    }n.||d<   |                     |                     ||                    }||                     |          nd}| 	                    |d          }| 
                    ||          S )a  
        fetches information on an order made by the user
        :see: https://docs.kucoin.com/futures/#get-details-of-a-single-order
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  r  z7 fetchOrder() requires parameter id or params.clientOidr?  r  )rp  r  r   r)   r  "futuresPrivateGetOrdersByClientOidrw  futuresPrivateGetOrdersOrderIdr\  r  r  )	r	  r)   r  r  r}  r  r  r\  r`  s	            r  fetch_orderzkucoinfutures.fetch_order  s    	: ..v{OTTM$"47-f#fggg#0GK YYv_'EFFF>>t{{7TZ?[?[\\HH!#GI::4;;wPV;W;WXXHX *0);V$$$$~~h77f555r  c                    |                      |d          }|                     ||          }|d         }|                     |dd          }|                      |d          }|                     |d          }|                     |          }|                      |d          }	|                      |d          }
|                      |d          }|                     |          }|                     |d	          }|                      |d
          }|                      |d          }|                      |d          }d }t          j        |d          ro|                      |d          }|d         r)t          j	        |t          j
        ||                    }n(t          j	        t          j
        ||          |          }|                     |d          }|                     |dd          }d }||rdnd}|rdn|}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%|          S )&Nr  r)   r?  r5  	createdAtr=  r  feeCurrencyfeer  
filledSizefilledValuer   rG  r9  isActivecancelExistFr  rY  canceled)r  rD  r  r,  r%  r.  r+  	updatedAtr  r<  r$  rD  filled	remainingr   r  )ro  r   r  lastTradeTimestampr  r  trades)r  r  r  rR  rY  rS  rU  r%   r  rV  
string_mulr  r  
safe_order)r	  orderr\  r{  r  r?  r5  r   r  r=  r  feeCurrencyIdrn  feeCostr<  rv  rD  r  rG  rr  rs  r   ro  r  r,  r%  r.  r+  r  s                                r  r  zkucoinfutures.parse_order  s   v ##E844!!(F33!$$UD)<<v..%%e[99	<<	**  00 v..((>>--m<<""5%00!!%00!!%66}55VS)) 	]++FNCCLh ]!,T73ElTZ3[3[\\!,W-?f-U-UW[\\ ??5*55nnUM5AA'5VVXF*6' C ((<<&&um<<$$UK88	??5*55__UL99
"//{CC  
' 
] 
 f 
 D	 

 ; 
  
 * 
 D 
 f 
 U 
  
 I 
 D 
 f 
  
  ! 
" # 
$ "&#61 
  
  
2 3  	r  c                    |                                   |                     |          }d|d         i}|                     |                     ||                    }|                     |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 )a  
        fetch the current funding rate
        :see: https://www.kucoin.com/docs/rest/futures-trading/funding-fees/get-current-funding-rate
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        r  r)   r  r  r  r  N
indexPriceinterestRateestimatedSettlePricer   r  r  valuefundingTimestampfundingDatetimenextFundingRatepredictedValuenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetime)rp  r\  (futuresPublicGetFundingRateSymbolCurrentrw  r  rR  rU  rY  )r	  r  r  r\  r}  r  r  r  s           r  fetch_funding_ratez kucoinfutures.fetch_funding_ratex  s    	V$$fTl
 @@WV\A]A]^^ x00,,T;??
D
fX&
 
 $	

 D
 #D
 
 
 4++D'::
  0
 t||,<==
 t//6FGG
 #D
 "4
 "4
  '!
" &t#
 	
r  c                 P   |d d d}|                      |d          }|                     |d          }|                     |          }|                                 }|                     |d          |d<   |                     |d          |d<   |||<   |                     |          S )N)r  r   r  r  r  availableBalancefreeaccountEquityrR  )r  r  rS  accountsafe_balance)r	  r  rZ  r  r  r   r  s          r  parse_balancezkucoinfutures.parse_balance  s    
 

 x00%%dJ77
&&z22,,..**41CDD++D/BBt  (((r  c                    |                                   |                     | j        d          }|                     | j        di           }|                     |d|          }|                     |d|          }|                     |          }d|d         i}|                     |                     ||                    }|                     |          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/funding/funding-overview/get-account-detail-futures
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        r   rM   r  r)   )rp  r  r  r  r   futuresPrivateGetAccountOverviewrw  r  )r	  r  defaultCodefetchBalanceOptionsr   r  r}  r  s           r  fetch_balancezkucoinfutures.fetch_balance  s     	&&t|V<<"oodlNBOO&&':FKPP<<==&&
 88Wf9U9UVV  !!(+++r  fromAccount	toAccountc                    |dk    r|dk    s|dk    r#|dk    r|dk    rt          | j        dz             |                                  |                     |          }|                     ||          }|                     |d          |d}|                     |                     ||                    }	|                     |	d	          }
|                     | 	                    |
|          | 
                    |          dd
d          S )a  
        transfer currency internally between wallets on the same account
        :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>`
        mainr   futuresr:   r8  zZ transfer() only supports transfers from contract(future) account to main(funding) accountr)   )r  r<  r  r7   )r<  r  r  )r   r)   rp  r  currency_to_precisionr  futuresPrivatePostTransferOutrw  r  parse_transferr  )r	  r   r<  r  r  r  r  amountToPrecisionr}  r  r  s              r  rx   zkucoinfutures.transfer  sO    I$:$:y@X@X]hlt]t]t  zE  IS  zS  zSTW  (D  D  E  E  E==&& 66tVDD((488'
 

 55dkk'66R6RSS x00{{4..tX>>''(9::#A
 A
   	r  r  c                     |                      |d          }|                     |d          ||                     |          |                     d |          d d d |                     |d          |d	S )Nru  applyIdr   )	r)   r   r  r  r<  r  r  r   r  )rR  r  rY  rS  )r	  rx   r  r   s       r  r  zkucoinfutures.parse_transfer  s     %%h<<	""8Y77"Y////h??&&x::

 

 
	
r  c                 8    ddi}|                      |||          S )N
PROCESSINGpending)r  )r	  r   statusess      r  parse_transfer_statusz#kucoinfutures.parse_transfer_status  s(    )
 &&999r  c                    |                                   d}|                     |dd          \  }}|r|                     d||||          S i }d}| |                     |          }|d         |d<   |||d<   |                     d||          \  }}|                     |                     ||                    }|                     |d	i           }	|                     |	d
g           }
| 	                    |
|||          S )a  
        :see: https://docs.kucoin.com/futures/#get-fills
        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]: End time in ms
        :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>`
        Frf   ri  Nr)   r  r  r  r  r[  )
rp  rq  r\  r\  handle_until_optionfuturesPrivateGetFillsrw  r  rx  parse_trades)r	  r  rf  rg  r  ri  r}  r\  r  r  ry  s              r  fetch_my_tradeszkucoinfutures.fetch_my_trades  s%    	88R\]]& 	d44_feUZ\bccc
 [[((F &tGH!&GI227GVLL..t{{7F/K/KLLD ~~h33gr22  >>>r  c                    |                                   |                     |          }d|d         i}|                     |                     ||                    }|                     |dg           }|                     ||||          S )a@  
        get the list of most recent trades for a particular symbol
        :see: https://www.kucoin.com/docs/rest/futures-trading/market-data/get-transaction-history
        :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  )rp  r\  futuresPublicGetTradeHistoryrw  rx  r  )	r	  r  rf  rg  r  r\  r}  r  ry  s	            r  fetch_tradeszkucoinfutures.fetch_trades`  s     	V$$fTl
 44T[[&5Q5QRR$ &"55  >>>r  c                 f   |                      |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          }|dk    rd }|                     |dd          }|@|                      |d          }t          j        ||	          }t          j        ||          }|                     ||||| 	                    |          |d         |||
||	||d|          S )Nr  r   tradeIdr)   r?  	liquidityr  r  rm  	dealValuerl  r=  	dealPricer  r<  r  ro  rn  sellr0  r/  feeRate)rD  r  rater5  	orderTypematchfundsr  rG  )r  r)   r|  r   r  r  r5  takerOrMakerr  r=  r<  rD  ro  )
r  r  r  rR  r  rS  r%   rz  
safe_traderY  )r	  trader\  r{  r)   r?  r  r   priceStringamountStringr  ro  feeCostStringr}  rn  r5  
costStringrG  contractCosts                      r  parse_tradezkucoinfutures.parse_trade  s   X ##E844!!(FC88y$77""5)44''{;;%%eT22	 )))g*=>>II))%==Iu$$9+@%,	((EE))%BBv..((66$ ,,UMBBM11-@@K"26&..fWoovf~%'((	:: C
 !!%==7??D''w@@
++FNCCL"-k<HHL +L,GGJ"Y//X&( " 
  
   	r  c                 6   |                                   i }d}| |                     |          }|d         |d<   |||d<   |||d<   |                     |                     ||                    }|d         d         }|                     ||||dd	i          S )
a  
        fetch all deposits made to an account
        :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
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        Nr)   r  pageSizer  r  r[  r5  r   )rp  r  futuresPrivateGetDepositListrw  parse_transactions	r	  r   rf  rg  r  r}  r  r  r`  s	            r  fetch_depositszkucoinfutures.fetch_deposits	  s     	}}T**H"*4.GJ"'GJ!&GI44T[[&5Q5QRR8  '0&&|XuefV_M`aaar  c                 6   |                                   i }d}| |                     |          }|d         |d<   |||d<   |||d<   |                     |                     ||                    }|d         d         }|                     ||||dd	i          S )
a  
        fetch all withdrawals made from an account
        :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
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        Nr)   r  r  r  r  r[  r5  
withdrawal)rp  r  futuresPrivateGetWithdrawalListrw  r  r  s	            r  fetch_withdrawalszkucoinfutures.fetch_withdrawals6	  s     	}}T**H"*4.GJ"'GJ!&GI77GV8T8TUU8  '0&&|XuefVbMcdddr  c                 P   |                                   |                     |          }|d         st          | j        dz             d|d         i}|                     |                     ||                    }|                     |d          }|                     ||          S )a  
        retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes for a single market
        :see: https://www.kucoin.com/docs/rest/futures-trading/risk-limit/get-futures-risk-limit-level
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `leverage tiers structure <https://docs.ccxt.com/#/?id=leverage-tiers-structure>`
        r8  z: fetchMarketLeverageTiers() supports contract markets onlyr  r)   r  )rp  r\  r   r)   (futuresPublicGetContractsRiskLimitSymbolrw  r  parse_market_leverage_tiersr  s          r  fetch_market_leverage_tiersz)kucoinfutures.fetch_market_leverage_tiersh	  s     	V$$j! 	eTW'ccdddfTl
 @@WV\A]A]^^$ x00//f===r  c                 h   g }t          dt          |                    D ]}||         }|                    |                     |d          |d         |                     |d          |                     |d          |                     |d          |                     |d          |d           |S )	z
         * @ignore
        :param dict info: Exchange market response for 1 market
        :param dict market: CCXT market
        r   r  r/  minRiskLimitmaxRiskLimitmaintainMarginr?  )tierr  minNotionalmaxNotionalmaintenanceMarginRater?  r  )rP  rQ  rW  rU  )r	  r  r\  r   r[  r  s         r  r  z)kucoinfutures.parse_market_leverage_tiers	  s    " q#d))$$ 
	 
	A7DLL((w77"6N#//nEE#//nEE)-)9)9$@P)Q)Q#//mDD      r  c                    |t          | j        dz             |                                  |                     |          }|d         d|                                 d}|                     |dd          }|                     |ddg          }|||d<   ||d	z   |d
<   |||d
<   ||d	z
  |d
<   |                     |                     ||                    }| 	                    |d          }	| 
                    |	|||          S )a  
        :see: https://www.kucoin.com/docs/rest/futures-trading/funding-fees/get-public-funding-history#request-url
        fetches historical funding rate prices
        :param str symbol: unified symbol of the market to fetch the funding rate history for
        :param int [since]: not used by kucuoinfutures
        :param int [limit]: the maximum amount of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>` to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: end time in ms
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>`
        Nz5 fetchFundingRateHistory() requires a symbol argumentr)   r   )r  rm  ro  rW  rX  rm  l    PRW ro  r  )r   r)   rp  r\  rt  r]  r  $futuresPublicGetContractFundingRatesrw  r  parse_funding_rate_histories)
r	  r  rf  rg  r  r\  r}  rW  r  r  s
             r  fetch_funding_rate_historyz(kucoinfutures.fetch_funding_rate_history	  s/    >#DG.e$efffV$$Tl##%%
 

 ##FGV<<6GV#455#GFO} %(@ @!GDM} %(@ @<<T[[RX=Y=YZZ x0000vueLLLr  c                     |                      |d          }|                     |d          }||                     ||          |                     |d          ||                     |          dS )N	timepointr  r  )r  r  r  r   r  )rR  r  rS  rU  rY  )r	  r  r\  r   r{  s        r  parse_funding_rate_historyz(kucoinfutures.parse_funding_rate_history	  sv    %%dK88	##D(33&&x88++D-@@"Y//
 
 	
r  c                 $   |                                   |                     |          }|                     |d          }|                     |dd          }|                     |ddg          }|'|                     |                                           }|d         d|dd}d}|r*|                     |                     ||                    }n)| 	                    |                     ||                    }| 
                    ||          S )	a   
        closes open positions for a market
        :see: https://www.kucoin.com/docs/rest/futures-trading/orders/place-order
        :param str symbol: Unified CCXT market symbol
        :param str side: not used by kucoinfutures closePositions
        :param dict [params]: extra parameters specific to the okx api endpoint
        :param str [params.clientOrderId]: client order id of the order
        :returns dict[]: `A list of position structures <https://docs.ccxt.com/#/?id=position-structure>`
        r  r
  FNr)   Tr\  )r  
closeOrderr  r5  )rp  r\  r  r  r  number_to_stringr  r  rw  r  r  )	r	  r  r  r  r\  r  r  r}  r  s	            r  close_positionzkucoinfutures.close_position	  s    	V$$((AANN66599	6FO#<==  11$**,,??MTl&	
 
  	S88Wf9U9UVVHH44T[[&5Q5QRRH&111r  )N)E__name__
__module____qualname__r  r  r   r	   rb  re  strr   listr  r  r  r   r  r   r  r   r   r  r  r   r  r  r  r  r   r   floatr
   r  r   r  r  rB  rI  r   rP  rO  ra  r   re  rg  rk  r  r  r   r  r  r   rx   r   r  r  r  r   r  r  r   r  r  r  r  r  r  r  __classcell__)r
  s   @r  r'   r'      s       { { { { {z	 #% 
 
 
 
6 $& \ \$v, \ \ \ \| !# 3 3 3 3  26DW[df 2H 2H# 2Hc 2HQT 2Hkoptku 2H 2H 2H 2Hh
 
 
4 
 
 
 
* 79 #
 #
# #
 #
 #
 #
J :>b / /s /3 /Y / / / /b 02  ;  ;3  ;f  ;  ;  ;  ;D 04B KH KHW KH7 KH KH KH KHZh h6 hV h h h hT 37TX\eg @ @C @s @RU @ @ @ @D 24 ;1 ;1S ;1 ;1 ;1 ;1z 26b 93 93w 93 93 93 93v\ \v \ \ \ \| gksu .. ..3 ..i ..y ..RW ..`c .. .. .. ..` @B ,' ,'D$6 ,' ,' ,' ,'\ x|  EG <, <,C <,y <,PY <,ch <,qt <, <, <, <,| 37r #1 #1s #1C #1 #1 #1 #1J /32 1 1 1 1 1 1B 68 G G G<N G G G GR@
 @
f @
HZ @
 @
 @
 @
D <@daenp d? d?S d? d?[^ d? d? d? d?L 154VZce Q Q# QS QPS Qjnotju Q Q Q Q* /3TXac Q Q Q3 Qc Qhlmrhs Q Q Q Q. %)R B6 B6c B6# B6 B6 B6 B6HA A A5 A A A AF 68 /
 /
 /
 /
 /
 /
b) ) ) ) ) $& !, !,( !, !, !, !,F [] " "S "% "c "c "an " " " "H
 
 
 
 
 
*: : : -1tRV_a D? D?c D? D?C D? D? D? D?L 6:UW "? "?3 "?s "?# "?\`af\g "? "? "? "?H~ ~ ~5 ~ ~ ~ ~@ *.Dt\^ 0b 0b3 0bc 0b 0bcghsct 0b 0b 0b 0bd -1tRV_a 0e 0ec 0e 0eC 0efjkvfw 0e 0e 0e 0ed ?A "> "># "> "> "> ">H     > 8<$]ajl ,M ,M ,MC ,MWZ ,M ,M ,M ,M\	
 	
v 	
 	
 	
 	
 =A 2 2S 2	 2PU 2 2 2 2 2 2 2 2r  r'   N)+ccxt.kucoinr   ccxt.abstract.kucoinfuturesr   ccxt.base.typesr   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#   ccxt.base.decimal_to_precisionr$   ccxt.base.preciser%   r'    r  r  <module>r     si         3 3 3 3 3 3 M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M  M       0 0 0 0 0 0 - - - - - - - - - - - - . . . . . . ' ' ' ' ' ' . . . . . . ) ) ) ) ) ) * * * * * * ) ) ) ) ) ) . . . . . . 1 1 1 1 1 1 ) ) ) ) ) ) 4 4 4 4 4 4 % % % % % %f'2 f'2 f'2 f'2 f'2FK f'2 f'2 f'2 f'2 f'2r  