diff --git a/kucoin/asyncio/__init__.py b/kucoin/asyncio/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/kucoin/asyncio/async_request/__init__.py b/kucoin/asyncio/async_request/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/kucoin/asyncio/async_request/async_request.py b/kucoin/asyncio/async_request/async_request.py new file mode 100644 index 0000000..0c15298 --- /dev/null +++ b/kucoin/asyncio/async_request/async_request.py @@ -0,0 +1,123 @@ +#!/usr/bin/python +# -*- coding:utf-8 -*- + +import json +import aiohttp +import hmac +import hashlib +import base64 +import time +from uuid import uuid1 +from urllib.parse import urljoin + + +try: + import pkg_resources + + version = 'v' + pkg_resources.get_distribution("kucoin-python").version +except (ModuleNotFoundError, pkg_resources.DistributionNotFound, NameError): + version = 'v1.0.0' + + +class KucoinAsyncRestApi(object): + + + def __init__(self, key='', secret='', passphrase='', url='', is_v1api=False): + """ + https://docs.kucoin.com + + :param key: Api Token Id (Mandatory) + :type key: string + :param secret: Api Secret (Mandatory) + :type secret: string + :param passphrase: Api Passphrase used to create API (Mandatory) + :type passphrase: string + """ + + if url: + self.url = url + else: + self.url = 'https://api.kucoin.com' + + self.key = key + self.secret = secret + self.passphrase = passphrase + self.is_v1api = is_v1api + + async def _request(self, method, uri, timeout=5, auth=True, params=None): + uri_path = uri + data_json = '' + if method in ['GET', 'DELETE']: + if params: + strl = [] + for key in sorted(params): + strl.append("{}={}".format(key, params[key])) + data_json += '&'.join(strl) + uri += '?' + data_json + uri_path = uri + else: + if params: + data_json = json.dumps(params) + + uri_path = uri + data_json + + headers = {} + if auth: + now_time = int(time.time()) * 1000 + str_to_sign = str(now_time) + method + uri_path + sign = base64.b64encode( + hmac.new(self.secret.encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha256).digest()) + if self.is_v1api: + headers = { + "KC-API-SIGN": sign.decode('utf-8'), + "KC-API-TIMESTAMP": str(now_time), + "KC-API-KEY": self.key, + "KC-API-PASSPHRASE": self.passphrase, + "Content-Type": "application/json" + } + else: + passphrase = base64.b64encode( + hmac.new(self.secret.encode('utf-8'), self.passphrase.encode('utf-8'), hashlib.sha256).digest()) + headers = { + "KC-API-SIGN": sign.decode('utf-8'), + "KC-API-TIMESTAMP": str(now_time), + "KC-API-KEY": self.key, + "KC-API-PASSPHRASE": passphrase.decode('utf-8'), + "Content-Type": "application/json", + "KC-API-KEY-VERSION": "2" + } + headers["User-Agent"] = "kucoin-python-sdk/" + version + url = urljoin(self.url, uri) + + async with aiohttp.ClientSession() as session: + async with session.request( + method, + url, + headers=headers, + data=data_json if method not in ['GET', 'DELETE'] else None, + timeout=timeout + ) as response: + return await self.check_response_data(response) + + @staticmethod + async def check_response_data(response): + if response.status == 200: + try: + data = await response.json() + except ValueError: + error_text = await response.text() + raise Exception(f"JSON decoding error: {error_text}") + else: + if data and data.get('code'): + if data.get('code') == '200000': + return data.get('data', data) + else: + message = data.get('message', response.text()) + raise Exception(f"API error {data.get('code')}: {message}") + else: + error_text = await response.text() + raise Exception(f"HTTP error {response.status}: {error_text}") + + @property + def return_unique_id(self): + return ''.join([each for each in str(uuid1()).split('-')]) diff --git a/kucoin/asyncio/client.py b/kucoin/asyncio/client.py new file mode 100644 index 0000000..5b6c622 --- /dev/null +++ b/kucoin/asyncio/client.py @@ -0,0 +1,31 @@ +from kucoin.asyncio.earn.earn import AsyncEarnData +from kucoin.asyncio.lending.lending import AsyncLendingData +from kucoin.asyncio.margin.margin import AsyncMarginData +from kucoin.asyncio.market.market import AsyncMarketData +from kucoin.asyncio.trade.trade import AsyncTradeData +from kucoin.asyncio.user.user import AsyncUserData + + +class User(AsyncUserData): + pass + + +class Trade(AsyncTradeData): + pass + + +class Market(AsyncMarketData): + pass + + +class Lending(AsyncLendingData): + pass + +class Earn(AsyncEarnData): + pass + + +class Margin(AsyncMarginData): + pass + + diff --git a/kucoin/asyncio/earn/__init__.py b/kucoin/asyncio/earn/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/kucoin/asyncio/earn/earn.py b/kucoin/asyncio/earn/earn.py new file mode 100644 index 0000000..c08e7ba --- /dev/null +++ b/kucoin/asyncio/earn/earn.py @@ -0,0 +1,117 @@ +from kucoin.asyncio.async_request.async_request import KucoinAsyncRestApi +import warnings + + +class AsyncEarnData(KucoinAsyncRestApi): + + async def subscribe_to_earn_fixed_income_products(self, productId, amount, accountType): + """ + Subscribe to Earn Fixed Income Products + see: https://www.kucoin.com/zh-hant/docs/rest/earn/general/subscribe-to-earn-fixed-income-products + """ + params = { + 'productId': productId, + 'amount': amount, + 'accountType': accountType, + } + return await self._request('POST', '/api/v1/earn/orders', params=params) + + async def redeem_by_earn_holding_id(self, orderId, amount, fromAccountType=None, confirmPunishRedeem=None): + """ + Redeem by Earn Holding ID + see: https://www.kucoin.com/zh-hant/docs/rest/earn/general/subscribe-to-earn-fixed-income-products + """ + params = { + 'orderId': orderId, + 'amount': amount, + } + if fromAccountType: + params['fromAccountType'] = fromAccountType + if confirmPunishRedeem: + params['confirmPunishRedeem'] = confirmPunishRedeem + + return await self._request('DELETE', '/api/v1/earn/orders', params=params) + + async def get_earn_redeem_preview_by_holding_id(self, orderId, fromAccountType=None): + """ + Get Earn Redeem Preview by Holding ID + see https://www.kucoin.com/docs/rest/earn/general/get-earn-redeem-preview-by-holding-id + """ + params = { + 'orderId': orderId, + } + if fromAccountType: + params['fromAccountType'] = fromAccountType + return await self._request('GET', '/api/v1/earn/redeem-preview', params=params) + + async def get_earn_savings_products(self, currency=None): + """ + Get Earn Savings Products + see https://www.kucoin.com/docs/rest/earn/kucoin-earn/get-earn-savings-products + """ + params = { + 'currency': currency, + } + params = {k: v for k, v in params.items() if v is not None} + return await self._request('GET', '/api/v1/earn/saving/products', params=params) + + async def get_earn_fixed_income_current_holdings(self, currentPage=None, pageSize=None, productId=None, productCategory=None, currency=None): + """ + Get Earn Fixed Income Current Holdings + see https://www.kucoin.com/docs/rest/earn/kucoin-earn/get-earn-fixed-income-current-holdings + """ + params = { + 'currentPage': currentPage, + 'pageSize': pageSize, + 'productId': productId, + 'productCategory': productCategory, + 'currency': currency + } + params = {k: v for k, v in params.items() if v is not None} + + return await self._request('GET', '/api/v1/earn/hold-assets', params=params) + + async def get_earn_limited_time_promotion_products(self, currency=None): + """ + Get Earn Limited-Time Promotion Products + + see https://www.kucoin.com/docs/rest/earn/kucoin-earn/get-earn-limited-time-promotion-products + """ + params = { + 'currency': currency + } + params = {k: v for k, v in params.items() if v is not None} + + return await self._request('GET', '/api/v1/earn/promotion/products', params=params) + + async def get_earn_kcs_staking_products(self, currency=None): + """ + Get Earn KCS Staking Products + see https://www.kucoin.com/docs/rest/earn/staking/get-earn-kcs-staking-products + """ + params = { + 'currency': currency + } + params = {k: v for k, v in params.items() if v is not None} + + return await self._request('GET', '/api/v1/earn/kcs-staking/products', params=params) + + async def get_earn_staking_products(self, currency=None): + """ + Get Earn Staking Products + see https://www.kucoin.com/docs/rest/earn/staking/get-earn-staking-products + """ + params = { + 'currency': currency + } + params = {k: v for k, v in params.items() if v is not None} + + return await self._request('GET', '/api/v1/earn/staking/products', params=params) + + async def get_earn_eth_staking_products(self): + """ + Get Earn ETH Staking Products + see https://www.kucoin.com/docs/rest/earn/staking/get-earn-eth-staking-products + """ + + return await self._request('GET', '/api/v1/earn/eth-staking/products') diff --git a/kucoin/asyncio/lending/__init__.py b/kucoin/asyncio/lending/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/kucoin/asyncio/lending/lending.py b/kucoin/asyncio/lending/lending.py new file mode 100644 index 0000000..b502e2c --- /dev/null +++ b/kucoin/asyncio/lending/lending.py @@ -0,0 +1,87 @@ +from kucoin.asyncio.async_request.async_request import KucoinAsyncRestApi +import warnings + + +class AsyncLendingData(KucoinAsyncRestApi): + + async def get_currency_information(self, currency): + """ + Get Currency Information + see:https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/get-currency-information + """ + params = { + 'currency': currency + } + return await self._request('GET', '/api/v3/project/list', params=params) + + async def get_interest_rates(self, currency): + """ + Get Interest Rates + see https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/get-interest-rates + """ + params = { + 'currency': currency + } + return await self._request('GET', '/api/v3/project/marketInterestRate', params=params) + + async def subscription(self, currency, interest_rate, size): + """ + Subscription + see: https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/subscription + """ + params = { + 'currency': currency, + 'interestRate': interest_rate, + 'size': size, + } + return await self._request('POST', '/api/v3/purchase', params=params) + + async def redemption(self, currency, purchase_order_no, size): + """ + Redemption + see: https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/redemption + """ + params = { + 'currency': currency, + 'purchaseOrderNo': purchase_order_no, + 'size': size, + } + return await self._request('POST', '/api/v3/redeem', params=params) + + async def modify_subscription_orders(self, currency, purchase_order_no, interest_rate): + """ + Modify Subscription Orders + see: https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/modify-subscription-orders + """ + params = { + 'currency': currency, + 'purchaseOrderNo': purchase_order_no, + 'interestRate': interest_rate, + } + return await self._request('POST', '/api/v3/lend/purchase/update', params=params) + + async def get_redemption_orders(self, currency,status, **kwargs): + """ + Get Redemption Orders + see https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/get-redemption-orders + """ + params = { + 'currency': currency, + 'status': status + } + if kwargs: + params.update(kwargs) + return await self._request('GET', '/api/v3/redeem/orders', params=params) + + async def get_subscription_orders(self, currency,status, **kwargs): + """ + Get Subscription Orders + see https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/get-subscription-orders + """ + params = { + 'currency': currency, + 'status': status + } + if kwargs: + params.update(kwargs) + return await self._request('GET', '/api/v3/purchase/orders', params=params) diff --git a/kucoin/asyncio/margin/__init__.py b/kucoin/asyncio/margin/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/kucoin/asyncio/margin/margin.py b/kucoin/asyncio/margin/margin.py new file mode 100644 index 0000000..0e75e42 --- /dev/null +++ b/kucoin/asyncio/margin/margin.py @@ -0,0 +1,1260 @@ +from kucoin.asyncio.async_request.async_request import KucoinAsyncRestApi +import warnings + + +class AsyncMarginData(KucoinAsyncRestApi): + + async def get_mark_price(self, symbol): + """ + https://docs.kucoin.com/#margin-info + :param symbol: symbol (Mandatory) + :type: str + :return: + { + "symbol": "USDT-BTC", + "granularity": 5000, + "timePoint": 1568701710000, + "value": 0.00009807 + } + """ + return await self._request('GET', '/api/v1/mark-price/{symbol}/current'.format(symbol=symbol)) + + async def get_margin_config(self): + """ + https://docs.kucoin.com/#get-margin-configuration-info + :return: + { + "currencyList": ["BTC","USDT","EOS"], + "warningDebtRatio": "0.8", + "liqDebtRatio": "0.9", + "maxLeverage": "3" + } + """ + return await self._request('GET', '/api/v1/margin/config') + + async def get_margin_account(self): + """ + https://docs.kucoin.com/#get-margin-account + :return: + { + "accounts": [ + { + "availableBalance": "990.11", + "currency": "USDT", + "holdBalance": "7.22", + "liability": "66.66", + "maxBorrowSize": "88.88", + "totalBalance": "997.33" + } + ], + "debtRatio": "0.33" + } + """ + return await self._request('GET', '/api/v1/margin/account') + + async def create_borrow_order(self, currency, order_type, size, **kwargs): + """ + https://docs.kucoin.com/#post-borrow-order + :param currency: Currency to Borrow (Mandatory) + :type: str + :param order_type: Type: FOK, IOC (Mandatory) + :type: str + :param size: Total size (Mandatory) + :type: float + :param kwargs: [Optional] maxRate, term + :return: + { + "orderId": "a2111213", + "currency": "USDT" + } + """ + warnings.warn("this function is deprecated, use margin_borrowing instead,We will be taking this API offline in the near future", DeprecationWarning) + params = { + 'currency': currency, + 'type': order_type, + 'size': size, + } + if kwargs: + params.update(kwargs) + return await self._request('POST', '/api/v1/margin/borrow', params=params) + + async def margin_borrowing(self, currency, timeinforce, size, isHf=False, **kwargs): + """ + Margin Trading(V3) + Margin Borrowing + https://www.kucoin.com/docs/rest/margin-trading/margin-trading-v3-/margin-borrowing + :param currency: Currency to Borrow (Mandatory) + :type: str + :param timeinforce: IOC, FOK (Mandatory) + :type: str + :param size: Total size (Mandatory) + :type: float + :param kwargs: [Optional] isIsolated, symbol + :return: see api doc + """ + params = { + 'currency': currency, + 'timeInForce': timeinforce, + 'size': size, + 'isHf': isHf + } + if kwargs: + params.update(kwargs) + return await self._request('POST', '/api/v3/margin/borrow', params=params) + + async def get_borrow_order(self, orderId): + """ + https://docs.kucoin.com/#get-borrow-order + :param orderId: Borrow order ID + :type: str + :return: + { + "currency": "USDT", + "filled": 1.009, + "matchList": [ + { + "currency": "USDT", + "dailyIntRate": "0.001", + "size": "12.9", + "term": 7, + "timestamp": "1544657947759", + "tradeId": "1212331" + } + ], + "orderId": "a2111213", + "size": "1.009", + "status": "DONE" + } + """ + warnings.warn("this function is deprecated, use get_margin_borrowing_history instead,We will be taking this API offline in the near future", DeprecationWarning) + params = { + 'orderId': orderId + } + + return await self._request('GET', '/api/v1/margin/borrow', params=params) + + async def get_margin_borrowing_history(self, currency, **kwargs): + """ + Get Margin Borrowing History + https://www.kucoin.com/docs/rest/margin-trading/margin-trading-v3-/get-margin-borrowing-history + :param currency: Currency + :param kwargs: [Optional] see Api Doc + """ + params = { + 'currency': currency + } + if kwargs: + params.update(kwargs) + return await self._request('GET', '/api/v3/margin/borrow', params=params) + + async def get_repay_record(self, **kwargs): + """ + https://docs.kucoin.com/#get-repay-record + :param kwargs: [Optional] currency, currentPage, pageSize + :return: + { + "currentPage": 0, + "items": [ + { + "accruedInterest": "0.22121", + "createdAt": "1544657947759", + "currency": "USDT", + "dailyIntRate": "0.0021", + "liability": "1.32121", + "maturityTime": "1544657947759", + "principal": "1.22121", + "repaidSize": "0", + "term": 7, + "tradeId": "1231141" + } + ], + "pageSize": 0, + "totalNum": 0, + "totalPage": 0 + } + """ + params = {} + if kwargs: + params.update(kwargs) + warnings.warn("this function is deprecated, use get_margin_account instead,We will be taking this API offline in the near future", DeprecationWarning) + return await self._request('GET', '/api/v1/margin/borrow/outstanding', params=params) + + async def get_repayment_record(self, **kwargs): + """ + https://docs.kucoin.com/#get-repayment-record + :param kwargs: [Optional] currency, currentPage, pageSize + :return: + { + "currentPage": 0, + "items": [ + { + "currency": "USDT", + "dailyIntRate": "0.0021", + "interest": "0.22121", + "principal": "1.22121", + "repaidSize": "0", + "repayTime": "1544657947759", + "term": 7, + "tradeId": "1231141" + } + ], + "pageSize": 0, + "totalNum": 0, + "totalPage": 0 + } + """ + warnings.warn("this function is deprecated,We will be taking this API offline in the near future", DeprecationWarning) + params = {} + if kwargs: + params.update(kwargs) + return await self._request('GET', '/api/v1/margin/borrow/repaid', params=params) + + async def click_to_repayment(self, currency, sequence, size): + """ + https://docs.kucoin.com/#one-click-repayment + :param currency: currency (Mandatory) + :type: str + :param sequence: Repayment strategy. (Mandatory) + RECENTLY_EXPIRE_FIRST: Time priority, namely to repay the loans of the nearest maturity time first, + HIGHEST_RATE_FIRST: Rate Priority: Repay the loans of the highest interest rate first. + :type: str + :param size: Repayment size (Mandatory) + :type: float + :return: + """ + warnings.warn("this function is deprecated, use repayment instead,We will be taking this API offline in the near future", DeprecationWarning) + params = { + 'currency': currency, + 'sequence': sequence, + 'size': size + } + return await self._request('POST', '/api/v1/margin/repay/all', params=params) + + async def repayment(self, currency, size, isIsolated=None, symbol=None, isHf=False): + """ + Repayment + https://www.kucoin.com/docs/rest/margin-trading/margin-trading-v3-/repayment + :param see api doc + :return: see api doc + """ + params = { + 'currency': currency, + 'size': size + } + if isIsolated: + params['isIsolated'] = isIsolated + if isHf: + params['isHf'] = isHf + if symbol: + params['symbol'] = symbol + return await self._request('POST', '/api/v3/margin/repay', params=params) + + async def get_repayment_history(self, currency, **kwargs): + """ + Get Repayment History + https://www.kucoin.com/docs/rest/margin-trading/margin-trading-v3-/get-repayment-history + """ + params = { + 'currency': currency, + } + + if kwargs: + params.update(kwargs) + return await self._request('GET', '/api/v3/margin/repay', params=params) + + async def get_cross_or_isolated_margin_interest_records(self, **kwargs): + """ + Get Cross/Isolated Margin Interest Records + https://www.kucoin.com/docs/rest/margin-trading/margin-trading-v3-/get-cross-isolated-margin-interest-records + """ + params = {} + if kwargs: + params.update(kwargs) + return await self._request('GET', '/api/v3/margin/interest', params=params) + + async def place_hf_order(self, symbol, side, clientOid='', **kwargs): + """ + Margin HF Trade + Place HF order + see: https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/place-hf-order + """ + params = { + 'symbol': symbol, + 'side': side, + } + if not clientOid: + clientOid = self.return_unique_id + params['clientOid'] = clientOid + if kwargs: + params.update(kwargs) + return await self._request('POST', '/api/v3/hf/margin/order', params=params) + + async def place_hf_order_test(self, symbol, side, clientOid='', **kwargs): + """ + Margin HF Trade + Place HF Order Test + see: https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/place-hf-order-test + """ + params = { + 'symbol': symbol, + 'side': side, + } + if not clientOid: + clientOid = self.return_unique_id + params['clientOid'] = clientOid + if kwargs: + params.update(kwargs) + return await self._request('POST', '/api/v3/hf/margin/order/test', params=params) + + async def repay_single_order(self, currency, tradeId, size): + """ + https://docs.kucoin.com/#repay-a-single-order + :param currency: currency (Mandatory) + :type: str + :param tradeId: Trade ID (Mandatory) + :type: str + :param size: Repayment size (Mandatory) + :type: float + :return: + """ + warnings.warn("this function is deprecated, use repayment instead,We will be taking this API offline in the near future", DeprecationWarning) + params = { + 'currency': currency, + 'tradeId': tradeId, + 'size': size + } + return await self._request('POST', '/api/v1/margin/repay/single', params=params) + + async def create_lend_order(self, currency, size, dailyIntRate, term): + """ + https://docs.kucoin.com/#post-lend-order + :param currency: Currency to lend (Mandatory) + :type: str + :param size: Total size (Mandatory) + :type: str + :param dailyIntRate: Daily interest rate. e.g. 0.002 is 0.2% (Mandatory) + :type: str + :param term: Term (Unit: Day) (Mandatory) + :type: int + :return: + { + "orderId": "5da5a4f0f943c040c2f8501e" + } + """ + warnings.warn("this function is deprecated,We will be taking this API offline in the near future", DeprecationWarning) + params = { + 'currency': currency, + 'size': size, + 'dailyIntRate': dailyIntRate, + 'term': term + } + return await self._request('POST', '/api/v1/margin/lend', params=params) + + async def cancel_lend_order(self, orderId): + """ + https://docs.kucoin.com/#cancel-lend-order + :param orderId: Lend order ID (Mandatory) + :type: str + :return: + """ + warnings.warn("this function is deprecated,We will be taking this API offline in the near future", DeprecationWarning) + return await self._request('DELETE', '/api/v1/margin/lend/{orderId}'.format(orderId=orderId)) + + async def set_auto_lend(self, currency, isEnable, **kwargs): + """ + https://docs.kucoin.com/#set-auto-lend + :param currency: currency (Mandatory) + :type: str + :param isEnable: Auto-lend enabled or not (Mandatory) + :type: bool + :param kwargs: [Required when isEnable is true] retainSize, dailyIntRate, term + :return: + """ + params = { + 'currency': currency, + 'isEnable': isEnable + } + if kwargs: + params.update(kwargs) + warnings.warn("this function is deprecated,We will be taking this API offline in the near future", DeprecationWarning) + return await self._request('POST', '/api/v1/margin/toggle-auto-lend', params=params) + + async def get_active_order(self, **kwargs): + """ + https://docs.kucoin.com/#get-active-order + :param kwargs: [Optional] currency, currentPage, pageSize + :return: + { + "currentPage": 1, + "pageSize": 1, + "totalNum": 1, + "totalPage": 1, + "items": [{ + "orderId": "5da59f5ef943c033b2b643e4", + "currency": "BTC", + "size": "0.51", + "filledSize": "0", + "dailyIntRate": "0.0001", + "term": 7, + "createdAt": 1571135326913 + }] + } + """ + params = {} + if kwargs: + params.update(kwargs) + warnings.warn("this function is deprecated,We will be taking this API offline in the near future", DeprecationWarning) + return await self._request('GET', '/api/v1/margin/lend/active', params=params) + + async def get_lent_history(self, **kwargs): + """ + https://docs.kucoin.com/#get-lent-history + :param kwargs: [Optional] currency, currentPage, pageSize + :return: + { + "currentPage": 1, + "pageSize": 1, + "totalNum": 1, + "totalPage": 1, + "items": [{ + "orderId": "5da59f5bf943c033b2b643da", + "currency": "BTC", + "size": "0.51", + "filledSize": "0.51", + "dailyIntRate": "0.0001", + "term": 7, + "createdAt": 1571135323984, + "status": "FILLED" + }] + } + """ + params = {} + if kwargs: + params.update(kwargs) + warnings.warn("this function is deprecated,We will be taking this API offline in the near future", DeprecationWarning) + return await self._request('GET', '/api/v1/margin/lend/done', params=params) + + async def get_active_list(self, **kwargs): + """ + https://docs.kucoin.com/#get-active-lend-order-list + :param kwargs: [Optional] currency, currentPage, pageSize + :return: + { + "currentPage": 1, + "pageSize": 1, + "totalNum": 1, + "totalPage": 1, + "items": [{ + "tradeId": "5da6dba0f943c0c81f5d5db5", + "currency": "BTC", + "size": "0.51", + "accruedInterest": "0", + "repaid": "0.10999968", + "dailyIntRate": "0.0001", + "term": 14, + "maturityTime": 1572425888958 + }] + } + """ + params = {} + if kwargs: + params.update(kwargs) + warnings.warn("this function is deprecated,We will be taking this API offline in the near future", DeprecationWarning) + return await self._request('GET', '/api/v1/margin/lend/trade/unsettled', params=params) + + async def get_settled_order(self, **kwargs): + """ + https://docs.kucoin.com/#get-settled-lend-order-history + :param kwargs: [Optional] currency, currentPage, pageSize + :return: + { + "currentPage": 1, + "pageSize": 1, + "totalNum": 1, + "totalPage": 1, + "items": [{ + "tradeId": "5da59fe6f943c033b2b6440b", + "currency": "BTC", + "size": "0.51", + "interest": "0.00004899", + "repaid": "0.510041641", + "dailyIntRate": "0.0001", + "term": 7, + "settledAt": 1571216254767, + "note": "The account of the borrowers reached a negative balance, and the system has supplemented the loss via the insurance fund. Deposit funds: 0.51." + }] + } + """ + params = {} + if kwargs: + params.update(kwargs) + warnings.warn("this function is deprecated,We will be taking this API offline in the near future.", DeprecationWarning) + return await self._request('GET', '/api/v1/margin/lend/trade/settled', params=params) + + async def get_lend_record(self, currency=None): + """ + https://docs.kucoin.com/#get-account-lend-record + :param currency: currency (Optional) + :type: str + :return: + [{ + "currency": "BTC", + "outstanding": "1.02", + "filledSize": "0.91000213", + "accruedInterest": "0.00000213", + "realizedProfit": "0.000045261", + "isAutoLend": false + }] + """ + params = {} + if currency: + params['currency'] = currency + warnings.warn("this function is deprecated,We will be taking this API offline in the near future.", DeprecationWarning) + return await self._request('GET', '/api/v1/margin/lend/assets', params=params) + + async def get_lending_market(self, currency, term=None): + """ + https://docs.kucoin.com/#lending-market-data + :param currency: currency (Mandatory) + :type: str + :param term: Term (Unit: Day) (Optional) + :type: int + :return: + [{ + "dailyIntRate": "0.0001", + "term": 7, + "size": "1.02" + }] + """ + params = { + 'currency': currency + } + if term: + params['term'] = term + warnings.warn("this function is deprecated,We will be taking this API offline in the near future.", DeprecationWarning) + return await self._request('GET', '/api/v1/margin/market', params=params) + + async def get_margin_data(self, currency): + """ + https://docs.kucoin.com/#margin-trade-data + :param currency: currency (Mandatory) + :type: str + :return: + [{ + "tradeId": "5da6dba0f943c0c81f5d5db5", + "currency": "BTC", + "size": "0.51", + "dailyIntRate": "0.0001", + "term": 14, + "timestamp": 1571216288958989641 + }] + """ + params = { + 'currency': currency + } + warnings.warn("this function is deprecated,We will be taking this API offline in the near future.", DeprecationWarning) + return await self._request('GET', '/api/v1/margin/trade/last', params=params) + + async def get_margin_risk_limit(self, marginModel='cross'): + """ + https://docs.kucoin.com/#margin-trade-data + :param marginModel: marginModel + :type: str + :return: + [{ + "currency": "BTC", + "borrowMaxAmount": "50", + "buyMaxAmount": "50", + "precision": 8 + }, + { + "currency": "SKL", + "borrowMaxAmount": "50000", + "buyMaxAmount": "51000", + "precision": 3 + }, + { + "currency": "USDT", + "borrowMaxAmount": "100000", + "buyMaxAmount": "10000000000", + "precision": 8 + }, + { + "currency": "ETH", + "borrowMaxAmount": "236", + "buyMaxAmount": "500", + "precision": 8 + }, + { + "currency": "LTC", + "borrowMaxAmount": "100", + "buyMaxAmount": "40", + "precision": 8 + }] + """ + params = { + 'marginModel': marginModel, + } + return await self._request('GET', '/api/v1/risk/limit/strategy', params=params) + + async def query_isolated_margin_trading_pair(self): + """ + https://docs.kucoin.com/#query-isolated-margin-trading-pair-configuration + :return: + [ + { + "symbol": "EOS-USDC", + "symbolName": "EOS-USDC", + "baseCurrency": "EOS", + "quoteCurrency": "USDC", + "maxLeverage": 10, + "flDebtRatio": "0.97", + "tradeEnable": true, + "autoRenewMaxDebtRatio": "0.96", + "baseBorrowEnable": true, + "quoteBorrowEnable": true, + "baseTransferInEnable": true, + "quoteTransferInEnable": true + }, + { + "symbol": "MANA-USDT", + "symbolName": "MANA-USDT", + "baseCurrency": "MANA", + "quoteCurrency": "USDT", + "maxLeverage": 10, + "flDebtRatio": "0.9", + "tradeEnable": true, + "autoRenewMaxDebtRatio": "0.96", + "baseBorrowEnable": true, + "quoteBorrowEnable": true, + "baseTransferInEnable": true, + "quoteTransferInEnable": true + } + ] + """ + return await self._request('GET', '/api/v1/isolated/symbols') + + async def query_isolated_margin_account_info(self, balance_currency=None): + """ + https://docs.kucoin.com/#query-isolated-margin-account-info + :param balance_currency: [Optional] The pricing coin, currently only supports USDT, KCS, and BTC. + Defaults to BTC if no value is passed. + :type: str + :return: + { + "totalConversionBalance": "3.4939947", + "liabilityConversionBalance": "0.00239066", + "assets": [ + { + "symbol": "MANA-USDT", + "status": "CLEAR", + "debtRatio": "0", + "baseAsset": { + "currency": "MANA", + "totalBalance": "0", + "holdBalance": "0", + "availableBalance": "0", + "liability": "0", + "interest": "0", + "borrowableAmount": "0" + }, + "quoteAsset": { + "currency": "USDT", + "totalBalance": "0", + "holdBalance": "0", + "availableBalance": "0", + "liability": "0", + "interest": "0", + "borrowableAmount": "0" + } + }, + { + "symbol": "EOS-USDC", + "status": "CLEAR", + "debtRatio": "0", + "baseAsset": { + "currency": "EOS", + "totalBalance": "0", + "holdBalance": "0", + "availableBalance": "0", + "liability": "0", + "interest": "0", + "borrowableAmount": "0" + }, + "quoteAsset": { + "currency": "USDC", + "totalBalance": "0", + "holdBalance": "0", + "availableBalance": "0", + "liability": "0", + "interest": "0", + "borrowableAmount": "0" + } + } + ] + } + """ + params = {} + if balance_currency: + params['balanceCurrency'] = balance_currency + return await self._request('GET', '/api/v1/isolated/accounts', params=params) + + async def query_single_isolated_margin_account_info(self, symbol): + """ + https://docs.kucoin.com/#query-single-isolated-margin-account-info + :param symbol: Trading pair, e.g.: BTC-USDT (Mandatory) + :type: str + :return: + { + "symbol": "MANA-USDT", + "status": "CLEAR", + "debtRatio": "0", + "baseAsset": { + "currency": "MANA", + "totalBalance": "0", + "holdBalance": "0", + "availableBalance": "0", + "liability": "0", + "interest": "0", + "borrowableAmount": "0" + }, + "quoteAsset": { + "currency": "USDT", + "totalBalance": "0", + "holdBalance": "0", + "availableBalance": "0", + "liability": "0", + "interest": "0", + "borrowableAmount": "0" + } + } + """ + return await self._request('GET', '/api/v1/isolated/account/{symbol}'.format(symbol=symbol)) + + async def create_isolated_margin_borrow_order(self, symbol, currency, size, borrow_strategy, **kwargs): + """ + https://docs.kucoin.com/#isolated-margin-borrowing + :param symbol: Trading pair, e.g.: BTC-USDT + :type: str + :param currency: Borrowed coin type + :type: str + :param size: Borrowed amount + :type: float + :param borrow_strategy: Borrowing strategy: FOK, IOC + :type: str + :param kwargs: maxRate, period + :return: + { + "orderId": "62baad0aaafc8000014042b3", + "currency": "USDT", + "actualSize": "10" + } + """ + params = { + 'symbol': symbol, + 'currency': currency, + 'size': size, + 'borrowStrategy': borrow_strategy + } + if kwargs: + params.update(kwargs) + warnings.warn("this function is deprecated, use margin_borrowing instead,We will be taking this API offline in the near future", DeprecationWarning) + return await self._request('POST', '/api/v1/isolated/borrow', params=params) + + async def query_outstanding_repayment_records(self, **kwargs): + """ + https://docs.kucoin.com/#query-outstanding-repayment-records + :param kwargs: symbol, currency, pageSize, currentPage + :return: + { + "currentPage": 1, + "pageSize": 10, + "totalNum": 6, + "totalPage": 1, + "items": [ + { + "loanId": "62aec83bb51e6f000169a3f0", + "symbol": "BTC-USDT", + "currency": "USDT", + "liabilityBalance": "10.02000016", + "principalTotal": "10", + "interestBalance": "0.02000016", + "createdAt": 1655621691869, + "maturityTime": 1656226491869, + "period": 7, + "repaidSize": "0", + "dailyInterestRate": "0.001" + }, + { + "loanId": "62aa94e52a3fbb0001277fd1", + "symbol": "BTC-USDT", + "currency": "USDT", + "liabilityBalance": "10.05166708", + "principalTotal": "10", + "interestBalance": "0.05166708", + "createdAt": 1655346405447, + "maturityTime": 1655951205447, + "period": 7, + "repaidSize": "0", + "dailyInterestRate": "0.001" + } + ] + } + """ + params = {} + if kwargs: + params.update(kwargs) + warnings.warn("this function is deprecated, use query_single_isolated_margin_account_info instead,We will be taking this API offline in the near future", DeprecationWarning) + return await self._request('GET', '/api/v1/isolated/borrow/outstanding', params=params) + + async def query_repayment_records(self, **kwargs): + """ + https://docs.kucoin.com/#query-repayment-records + :param kwargs: symbol, currency, pageSize, currentPage + :return: + { + "currentPage": 1, + "pageSize": 10, + "totalNum": 30, + "totalPage": 3, + "items": [ + { + "loanId": "628df5787818320001c79c8b", + "symbol": "BTC-USDT", + "currency": "USDT", + "principalTotal": "10", + "interestBalance": "0.07000056", + "repaidSize": "10.07000056", + "createdAt": 1653470584859, + "period": 7, + "dailyInterestRate": "0.001", + "repayFinishAt": 1654075506416 + }, + { + "loanId": "628c570f7818320001d52b69", + "symbol": "BTC-USDT", + "currency": "USDT", + "principalTotal": "11", + "interestBalance": "0.07699944", + "repaidSize": "11.07699944", + "createdAt": 1653364495783, + "period": 7, + "dailyInterestRate": "0.001", + "repayFinishAt": 1653969432251 + } + ] + } + """ + params = {} + if kwargs: + params.update(kwargs) + warnings.warn("this function is deprecated,We will be taking this API offline in the near future", DeprecationWarning) + return await self._request('GET', '/api/v1/isolated/borrow/repaid', params=params) + + async def quick_repayment(self, symbol, currency, size, seq_strategy): + """ + https://docs.kucoin.com/#quick-repayment + :param symbol: Trading pair, e.g.: BTC-USDT (Mandatory) + :type: str + :param currency: Repayment coin type + :type: str + :param size: Repayment amount + :type: float + :param seq_strategy: Repayment sequence strategy, + RECENTLY_EXPIRE_FIRST: Maturity date priority (the loan with the closest maturity is repaid first), + HIGHEST_RATE_FIRST: Interest rate priority (the loan with the highest interest rate is repaid first) + :type: str + :return:None + """ + params = { + 'symbol': symbol, + 'currency': currency, + 'size': size, + 'seqStrategy': seq_strategy + } + warnings.warn("this function is deprecated, use repayment instead,We will be taking this API offline in the near future", DeprecationWarning) + return await self._request('POST', '/api/v1/isolated/repay/all', params=params) + + async def single_repayment(self, symbol, currency, size, loan_id): + """ + https://docs.kucoin.com/#single-repayment + :param symbol: Trading pair, e.g.: BTC-USDT (Mandatory) + :type: str + :param currency: Repayment coin type + :type: str + :param size: Repayment amount + :type: float + :param loan_id: Trade order number; when this field is configured, the sequence strategy is invalidated + :type: str + :return:None + """ + params = { + 'symbol': symbol, + 'currency': currency, + 'size': size, + 'loanId': loan_id + } + warnings.warn("this function is deprecated, use repayment instead,We will be taking this API offline in the near future", DeprecationWarning) + return await self._request('POST', '/api/v1/isolated/repay/single', params=params) + + async def get_etf_info(self, currency=None): + """ + Get Leveraged Token Info + https://www.kucoin.com/docs/rest/margin-trading/margin-info/get-leveraged-token-info + :param currency: if empty query all currencies + :return: + { + "success": true, + "code": "200", + "msg": "success", + "retry": false, + "data": [ + { + "currency": "BTCUP", //currency + "netAsset": 0.001,//Net worth + "targetLeverage": "2-4", //Target leverage + "actualLeverage": "2.33", //Actual leverage + "assetsUnderManagement": //The amount of currency issued + "basket": "-78.671762 XBTUSDTM" //basket information + } + ] + } + """ + params = {} + if currency: + params["currency"] = currency + + return await self._request('GET', '/api/v3/etf/info', params=params) + + async def get_margin_account_Detail(self, quoteCurrency=None, queryType=None): + """ + Get Account Detail - Cross Margin + https://www.kucoin.com/docs/rest/funding/funding-overview/get-account-detail-cross-margin + :param quoteCurrency: quote currency, currently only supports USDT, KCS, BTC, USDT as default + :param queryType: Query account type (default MARGIN), MARGIN - only query low frequency cross margin account, MARGIN_V2-only query high frequency cross margin account, ALL - consistent aggregate query with the web side + :return: + { + "success": true, + "code": "200", + "msg": "success", + "retry": false, + "data": { + "timestamp": 1669708513820, + "currentPage": 1, + "pageSize": 100, + "totalNum": 1, + "totalPage": 1, + "items": [ + { + "totalLiabilityOfQuoteCurrency": "0.976", //Total Liability in Quote Currency + "totalAssetOfQuoteCurrency": "1.00", //Total Assets in Quote Currency + "debtRatio": "0.976", //debt ratio + "status": "LIQUIDATION", //Position status; EFFECTIVE-effective, BANKRUPTCY-bankruptcy liquidation, LIQUIDATION-closing, REPAY-repayment, BORROW borrowing + "assets": [ + { + "currency": "BTC", + "borrowEnabled": true, + "repayEnabled": true, + "transferEnabled": false, + "borrowed": "0.976", + "totalAsset": "1.00", //Total Assets + "available": "0.024", //Account available assets (total assets - frozen) + "hold": "0", //Account frozen assets + "maxBorrowSize": "0" //The user's remaining maximum loan amount + } + ] + } + ] + } + } + """ + params = {} + if quoteCurrency: + params["quoteCurrency"] = quoteCurrency + if queryType: + params["queryType"] = queryType + + return await self._request('GET', '/api/v3/margin/accounts', params=params) + + async def get_isolated_margin_account_detail(self, quoteCurrency=None, queryType=None, symbol=None): + """ + Get Account Detail - Isolated Margin + https://www.kucoin.com/docs/rest/funding/funding-overview/get-account-detail-isolated-margin + :param quoteCurrency: quote currency, currently only supports USDT, KCS, BTC, default is USDT + :param symbol: For isolated trading pairs, query all without passing + :param queryType: Query account type (default MARGIN), ISOLATED- - only query low frequency isolated margin account, ISOLATED_V2-only query high frequency isolated margin account, ALL - consistent aggregate query with the web side + :return: + { + "code": "200000", + "data": [ + { + "totalAssetOfQuoteCurrency": "3.4939947", + "totalLiabilityOfQuoteCurrency": "0.00239066", + "timestamp": 1668062174000, + "assets": [ + { + "symbol": "MANA-USDT", + "debtRatio": "0", + "status": "BORROW", + "baseAsset": { + "currency": "MANA", + "borrowEnabled": true, + "repayEnabled": true, + "transferEnabled": true, + "borrowed": "0", + "totalAsset": "0", + "available": "0", + "hold": "0", + "maxBorrowSize": "1000" + }, + "quoteAsset": { + "currency": "USDT", + "borrowEnabled": true, + "repayEnabled": true, + "transferEnabled": true, + "borrowed": "0", + "totalAsset": "0", + "available": "0", + "hold": "0", + "maxBorrowSize": "50000" + } + } + ] + } + ] + } + """ + params = {} + if quoteCurrency: + params["quoteCurrency"] = quoteCurrency + if queryType: + params["queryType"] = queryType + if symbol: + params["symbol"] = symbol + + return await self._request('GET', '/api/v3/isolated/accounts', params=params) + + async def get_margin_currencies(self, isIsolated, currency=None, symbol=None): + """ + Get Cross/Isolated Margin Risk Limit/Currency config + https://www.kucoin.com/docs/rest/margin-trading/margin-info/get-cross-isolated-margin-risk-limit-currency-config + :param isIsolated: true - isolated, false - cross ; default false + :param symbol: symbol, required for isolated margin accounts + :param currency: currency + :return: + // CROSS MARGIN RESPONSES + { + "success": true, + "code": "200", + "msg": "success", + "retry": false, + "data": [ + { + "timestamp": 1697783812257, + "currency": "XMR", + "borrowMaxAmount": "999999999999999999", + "buyMaxAmount": "999999999999999999", + "holdMaxAmount": "999999999999999999", + "borrowCoefficient": "0.5", + "marginCoefficient": "1", + "precision": 8, + "borrowMinAmount": "0.001", + "borrowMinUnit": "0.001", + "borrowEnabled": true + } + ] + } + + // ISOLATED MARGIN RESPONSES + { + "success": true, + "code": "200", + "msg": "success", + "retry": false, + "data": [ + { + "timestamp": 1697782543851, + "symbol": "LUNC-USDT", + "baseMaxBorrowAmount": "999999999999999999", + "quoteMaxBorrowAmount": "999999999999999999", + "baseMaxBuyAmount": "999999999999999999", + "quoteMaxBuyAmount": "999999999999999999", + "baseMaxHoldAmount": "999999999999999999", + "quoteMaxHoldAmount": "999999999999999999", + "basePrecision": 8, + "quotePrecision": 8, + "baseBorrowCoefficient": "1", + "quoteBorrowCoefficient": "1", + "baseMarginCoefficient": "1", + "quoteMarginCoefficient": "1", + "baseBorrowMinAmount": null, + "baseBorrowMinUnit": null, + "quoteBorrowMinAmount": "0.001", + "quoteBorrowMinUnit": "0.001", + "baseBorrowEnabled": false, + "quoteBorrowEnabled": true + } + ] + } + """ + params = {"isIsolated": isIsolated} + if currency: + params["currency"] = currency + if symbol: + params["symbol"] = symbol + + return await self._request('GET', '/api/v3/margin/currencies', params=params) + + async def get_interest_rates(self, currency): + """ + Get Interest Rates + https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/get-interest-rates + + :param currency: currency + :return: + [ + { + "time": "202303261200", + "marketInterestRate": "0.003" + }, + { + "time": "202303261300", + "marketInterestRate": "0.004" + } + ] + """ + params = {"currency": currency} + + return await self._request('GET', '/api/v3/project/marketInterestRate', params=params) + + async def get_active_hf_order_symbols(self, tradeType): + """ + Get Active HF Order Symbols + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-active-hf-order-symbols + """ + params = {"tradeType": tradeType} + return await self._request('GET', '/api/v3/hf/margin/order/active/symbols', params=params) + + async def get_cross_margin_trading_pairs_configuration(self, symbol=None): + """ + Get Cross Margin Trading Pairs Configuration + https://www.kucoin.com/docs/rest/margin-trading/margin-trading-v3-/get-cross-margin-trading-pairs-configuration + """ + params = {} + if symbol: + params = {"symbol": symbol} + return await self._request('GET', '/api/v3/margin/symbols', params=params) + + + async def modify_leverage_multiplier(self, leverage, isIsolated=False,symbol=None): + """ + Modify Leverage Multiplier + https://www.kucoin.com/docs/rest/margin-trading/margin-trading-v3-/modify-leverage-multiplier + """ + params = { + 'leverage': leverage, + 'isIsolated': isIsolated, + } + if symbol: + params['symbol']=symbol + return await self._request('POST', '/api/v3/position/update-user-leverage', params=params) + + + async def get_information_onoff_exchange_funding_and_loans(self): + """ + Get information on off-exchange funding and loans + https://www.kucoin.com/zh-hant/docs/rest/vip-lending/get-information-on-off-exchange-funding-and-loans + """ + return await self._request('GET', '/api/v1/otc-loan/loan') + + async def get_information_on_accounts_involved_in_off_exchange_loans(self): + """ + Get information on accounts involved in off-exchange loans + https://www.kucoin.com/docs/rest/vip-lending/get-information-on-accounts-involved-in-off-exchange-loans + """ + return await self._request('GET', '/api/v1/otc-loan/accounts') + + async def cancel_hf_order_by_orderid(self, orderId,symbol): + """ + Cancel HF order by orderId + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/cancel-hf-order-by-orderid + """ + params = { + 'symbol': symbol + } + return await self._request('DELETE', '/api/v3/hf/margin/orders/{orderId}'.format(orderId=orderId),params=params) + + async def cancel_hf_order_by_clientoid(self, clientOid,symbol): + """ + Cancel HF order by clientOid + https://www.kucoin.com/zh-hant/docs/rest/margin-trading/margin-hf-trade/cancel-hf-order-by-clientoid + """ + params = { + 'symbol': symbol + } + return await self._request('DELETE', '/api/v3/hf/margin/orders/client-order/{clientOid}'.format(clientOid=clientOid),params=params) + + async def cancel_all_hf_orders_by_symbol(self, tradeType,symbol): + """ + Cancel all HF orders by symbol + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/cancel-all-hf-orders-by-symbol + """ + params = { + 'symbol': symbol, + 'tradeType': tradeType + } + return await self._request('DELETE', '/api/v3/hf/margin/orders',params=params) + + async def get_active_hf_orders_list(self, tradeType,symbol): + """ + Get Active HF Orders List + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-active-hf-orders-list + """ + params = { + 'symbol': symbol, + 'tradeType': tradeType + } + return await self._request('GET', '/api/v3/hf/margin/orders/active',params=params) + + + async def get_hf_filled_list(self, tradeType,symbol): + """ + Get HF Filled List + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-hf-filled-list + """ + params = { + 'symbol': symbol, + 'tradeType': tradeType + } + return await self._request('GET', '/api/v3/hf/margin/orders/done',params=params) + + async def get_hf_order_details_by_orderid(self, orderId,symbol): + """ + Get HF Order details by orderId + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-hf-order-details-by-orderid + """ + params = { + 'symbol': symbol, + } + return await self._request('GET', f'/api/v3/hf/margin/orders/{orderId}',params=params) + + + async def get_hf_order_details_by_clientoid(self, clientOid,symbol): + """ + Get HF order details by clientOid + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-hf-order-details-by-clientoid + """ + params = { + 'symbol': symbol + } + return await self._request('GET', f'/api/v3/hf/margin/orders/client-order/{clientOid}',params=params) + + async def get_hf_transaction_records(self,symbol): + """ + Get HF transaction records + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-hf-transaction-records + """ + params = { + 'symbol': symbol + } + return await self._request('GET', f'/api/v3/hf/margin/fills',params=params) \ No newline at end of file diff --git a/kucoin/asyncio/market/__init__.py b/kucoin/asyncio/market/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/kucoin/asyncio/market/market.py b/kucoin/asyncio/market/market.py new file mode 100644 index 0000000..2678a26 --- /dev/null +++ b/kucoin/asyncio/market/market.py @@ -0,0 +1,554 @@ +import warnings +from kucoin.asyncio.async_request.async_request import KucoinAsyncRestApi + + +class AsyncMarketData(KucoinAsyncRestApi): + + async def get_symbol_list(self, **kwargs): + """ + https://docs.kucoin.com/#get-symbols-list + :param kwargs: [Optional] market + :return: + [ + { + "symbol": "BTC-USDT", + "name": "BTC-USDT", + "baseCurrency": "BTC", + "quoteCurrency": "USDT", + "baseMinSize": "0.00000001", + "quoteMinSize": "0.01", + "baseMaxSize": "10000", + "quoteMaxSize": "100000", + "baseIncrement": "0.00000001", + "quoteIncrement": "0.01", + "priceIncrement": "0.00000001", + "feeCurrency": "USDT", + "enableTrading": true, + "isMarginEnabled": true, + "priceLimitRate": "0.1" + } + ] + """ + params = {} + if kwargs: + params.update(kwargs) + return await self._request('GET', '/api/v1/symbols', params=params) + + async def get_ticker(self, symbol): + """ + https://docs.kucoin.com/#get-ticker + :param symbol: symbol (Mandatory) + :type: str + :return: + { + "sequence": "1550467636704", + "bestAsk": "0.03715004", + "size": "0.17", + "price": "0.03715005", + "bestBidSize": "3.803", + "bestBid": "0.03710768", + "bestAskSize": "1.788", + "time": 1550653727731 + + } + """ + params = { + 'symbol': symbol + } + return await self._request('GET', '/api/v1/market/orderbook/level1', params=params) + + async def get_all_tickers(self): + """ + https://docs.kucoin.com/#get-all-tickers + :return: + { + "time": 1550653727731, + "ticker": [ + { + "symbol": "BTC-USDT", + "symbolName": "BTC-USDT", + "buy": "0.00001191", + "sell": "0.00001206", + "changeRate": "0.057", + "changePrice": "0.00000065", + "high": "0.0000123", + "low": "0.00001109", + "vol": "45161.5073", + "volValue": "2127.28693026”, + "last": "0.00001204" + }, + { + "symbol": "BCD-BTC", + "symbolName": "BCD-BTC", + "buy": "0.00018564", + "sell": "0.0002", + "changeRate": "-0.0753", + "changePrice": "-0.00001522", + "high": "0.00021489", + "low": "0.00018351", + "vol": "72.99679763", + "volValue": "2127.28693026”, + "last": "0.00018664" + } + ] + } + """ + return await self._request('GET', '/api/v1/market/allTickers') + + async def get_24h_stats(self, symbol): + """ + https://docs.kucoin.com/#get-24hr-stats + :param symbol: symbol (Mandatory) + :type: str + :return: + { + "symbol": "ETH-BTC", // symbol + "high": "0.03736329", // 24h highest price + "vol": "2127.286930263025", // 24h volume,the aggregated trading volume in ETH + "volValue": "43.58567564", // 24h total, the trading volume in quote currency of last 24 hours + "last": "0.03713983", // last price + "low": "0.03651252", // 24h lowest price + "buy": "0.03712118", // bestAsk + "sell": "0.03713983", // bestBid + "changePrice": "0.00037224", // 24h change price + "averagePrice": "8699.24180977",//24h average transaction price yesterday + "time": 1550847784668, //time + "changeRate": "0.0101" // 24h change rate + } + """ + params = { + 'symbol': symbol + } + return await self._request('GET', '/api/v1/market/stats', params=params) + + async def get_market_list(self): + """ + https://docs.kucoin.com/#get-market-list + :return: + [ + "BTC", + "KCS", + "USDS", //SC has been changed to USDS + "ALTS" //ALTS market includes ETH, NEO, TRX + ] + """ + return await self._request('GET', '/api/v1/markets') + + async def get_part_order(self, pieces, symbol): + """ + https://docs.kucoin.com/#get-part-order-book-aggregated + :param pieces: pieces of data (ask and bid data) on the order book (Mandatory) + :type: int + :param symbol: symbol + :type: str + :return: + { + "sequence": "3262786978", + "time": 1550653727731, + "bids": [["6500.12", "0.45054140"], + ["6500.11", "0.45054140"]], //[price,size] + "asks": [["6500.16", "0.57753524"], + ["6500.15", "0.57753524"]] + } + """ + params = { + 'symbol': symbol + } + return await self._request('GET', '/api/v1/market/orderbook/level2_{pieces}'.format(pieces=pieces), params=params) + + async def get_aggregated_orderv3(self, symbol): + """ + https://docs.kucoin.com/#get-full-order-book-aggregated + :param symbol: symbol (Mandatory) + :type: str + :return: + { + "sequence": "3262786978", + "time": 1550653727731, + "bids": [["6500.12", "0.45054140"], + ["6500.11", "0.45054140"]], //[price,size] + "asks": [["6500.16", "0.57753524"], + ["6500.15", "0.57753524"]] + } + """ + params = { + 'symbol': symbol + } + return await self._request('GET', '/api/v3/market/orderbook/level2', params=params) + + async def get_atomic_orderv3(self, symbol): + """ + https://docs.kucoin.com/#get-full-order-book-atomic + :param symbol: symbol (Mandatory) + :type: str + :return: + { + "data": { + "sequence": "1573503933086", + "asks": [ + [ + "5e0d672c1f311300093ac522", //orderId + "0.1917", //price + "390.9275", //size + "1577936689346546088" //time,nanoseconds + ], + [ + "5e0d672891432f000819ecc3", + "0.19171", + "1456.1316", + "1577936685718811031" + ] + ], + "bids": [ + [ + "5e0d672cdc53860007f30262", + "0.19166", + "178.1936", + "1577936689166023452" + ], + [ + "5e0d671a91432f000819d1b0", + "0.19165", + "583.6298", + "1577936671595901518" + ] + ], + "time": 1577936685107 + } + } + """ + return await self._request('GET', f'/api/v3/market/orderbook/level3?symbol={symbol}') + + async def get_atomic_order(self, symbol): + """ + https://docs.kucoin.com/#get-full-order-book-atomic + :param symbol: symbol (Mandatory) + :type: str + :return: + { + "data": { + "sequence": "1573503933086", + "asks": [ + [ + "5e0d672c1f311300093ac522", //orderId + "0.1917", //price + "390.9275", //size + "1577936689346546088" //time,nanoseconds + ], + [ + "5e0d672891432f000819ecc3", + "0.19171", + "1456.1316", + "1577936685718811031" + ] + ], + "bids": [ + [ + "5e0d672cdc53860007f30262", + "0.19166", + "178.1936", + "1577936689166023452" + ], + [ + "5e0d671a91432f000819d1b0", + "0.19165", + "583.6298", + "1577936671595901518" + ] + ], + "time": 1577936685107 + } + } + """ + return await self._request('GET', f'/api/v1/market/orderbook/level3?symbol={symbol}') + + async def get_trade_histories(self, symbol): + """ + https://docs.kucoin.com/#get-trade-histories + :param symbol: symbol (Mandatory) + :type: str + :return: + [ + { + "sequence": "1545896668571", + "price": "0.07", //Filled price + "size": "0.004", //Filled amount + "side": "buy", //Filled side. The filled side is set to the taker by default. + "time": 1545904567062140823 //Transaction time + }, + { + "sequence": "1545896668578", + "price": "0.054", + "size": "0.066", + "side": "buy", + "time": 1545904581619888405 + } + ] + """ + params = { + 'symbol': symbol + } + return await self._request('GET', '/api/v1/market/histories', params=params) + + async def get_kline(self, symbol, kline_type, **kwargs): + """ + https://docs.kucoin.com/#get-klines + :param symbol: symbol (Mandatory) + :type: str + :param kline_type: Type of candlestick patterns (Mandatory) + :type: str + :param kwargs: [Optional] startAt, endAt, currentPage, pageSize + :return: + [ + [ + "1545904980", //Start time of the candle cycle + "0.058", //opening price + "0.049", //closing price + "0.058", //highest price + "0.049", //lowest price + "0.018", //Transaction amount + "0.000945" //Transaction volume + ], + [ + "1545904920", + "0.058", + "0.072", + "0.072", + "0.058", + "0.103", + "0.006986" + ] + ] + """ + params = { + 'symbol': symbol, + 'type': kline_type + } + if kwargs: + params.update(kwargs) + return await self._request('GET', '/api/v1/market/candles', params=params) + + async def get_currencies(self): + """ + https://docs.kucoin.com/#get-currencies + :return: + [{ + "currency": "BTC", + "name": "BTC", + "fullName": "Bitcoin", + "precision": 8, + "withdrawalMinSize": "0.002", + "withdrawalMinFee": "0.0005", + "isWithdrawEnabled": true, + "isDepositEnabled": true, + "isMarginEnabled": true, + "isDebitEnabled": true + }, + { + + "currency": "ETH", + "name": "ETH", + "fullName": "Ethereum", + "precision": 8, + "withdrawalMinSize": "0.02", + "withdrawalMinFee": "0.01", + "isWithdrawEnabled": true, + "isDepositEnabled": true, + "isMarginEnabled": true, + "isDebitEnabled": true + + }] + """ + return await self._request('GET', '/api/v1/currencies') + + async def get_currency_detail(self, currency, chain=None): + """ + https://docs.kucoin.com/#get-currency-detail + :param currency: currency (Mandatory) + :type: str + :param chain: [Optional] Support for querying the chain of currency, e.g. The available value for USDT are OMNI, + ERC20, TRC20. This only apply for multi-chain currency, and there is no need for single chain currency. + :type: str + :return: + { + "currency": "BTC", + "name": "BTC", + "fullName": "Bitcoin", + "precision": 8, + "withdrawalMinSize": "0.002", + "withdrawalMinFee": "0.0005", + "isWithdrawEnabled": true, + "isDepositEnabled": true, + "isMarginEnabled": true, + "isDebitEnabled": true + } + """ + warnings.warn("The 'get_currency_detail' method is deprecated, use 'get_currency_detail_v2' instead", + DeprecationWarning) + params = {} + if chain: + params['chain'] = chain + return await self._request('GET', '/api/v1/currencies/{currency}'.format(currency=currency), params=params) + + async def get_currency_detail_v2(self, currency, chain=None): + """ + https://docs.kucoin.com/#get-currency-detail-recommend + :param currency: currency (Mandatory) + :type: str + :param chain: [Optional] Support for querying the chain of currency, return the currency details of all chains by default. + :type: str + :return: + { + "currency": "BTC", + "name": "BTC", + "fullName": "Bitcoin", + "precision": 8, + "confirms": null, + "contractAddress": null, + "isMarginEnabled": true, + "isDebitEnabled": true, + "chains": [ + { + "chainName": "BTC", + "withdrawalMinSize": "0.0008", + "withdrawalMinFee": "0.0005", + "isWithdrawEnabled": true, + "isDepositEnabled": true, + "confirms": 2, + "contractAddress": "" + }, + { + "chainName": "KCC", + "withdrawalMinSize": "0.0008", + "withdrawalMinFee": "0.00002", + "isWithdrawEnabled": true, + "isDepositEnabled": true, + "confirms": 20, + "contractAddress": "" + }, + { + "chainName": "TRC20", + "withdrawalMinSize": "0.0008", + "withdrawalMinFee": "0.0004", + "isWithdrawEnabled": false, + "isDepositEnabled": true, + "confirms": 1, + "contractAddress": "" + }, + { + "chainName": "BTC-Segwit", + "withdrawalMinSize": "0.0008", + "withdrawalMinFee": "0.0005", + "isWithdrawEnabled": true, + "isDepositEnabled": true, + "confirms": 2, + "contractAddress": "" + } + ] + } + """ + params = {} + if chain: + params['chain'] = chain + return await self._request('GET', '/api/v2/currencies/{currency}'.format(currency=currency), params=params) + + + async def get_fiat_price(self, **kwargs): + """ + https://docs.kucoin.com/#get-fiat-price + :param kwargs: [Optional] base, currencies + :return: + { + "BTC": "3911.28000000", + "ETH": "144.55492453", + "LTC": "48.45888179", + "KCS": "0.45546856" + } + """ + params = {} + if kwargs: + params.update(kwargs) + return await self._request('GET', '/api/v1/prices', params=params) + + async def get_server_timestamp(self): + """ + https://docs.kucoin.com/#server-time + + get server timestamp + :return: 1570609496404 + """ + return await self._request('GET', '/api/v1/timestamp', auth=False) + + async def get_server_status(self): + """ + https://docs.kucoin.com/#server-time + + get server timestamp + :return: + { + "status": "open", //open, close, cancelonly + "msg": "upgrade match engine" //remark for operation + } + """ + return await self._request('GET', '/api/v1/status', auth=False) + + async def get_symbol_list_v2(self, **kwargs): + """ + https://docs.kucoin.com/#get-symbols-list + :param kwargs: [Optional] market + :return: + [ + { + "symbol": "GALAX-USDT", + "name": "GALA-USDT", + "baseCurrency": "GALAX", + "quoteCurrency": "USDT", + "feeCurrency": "USDT", + "market": "USDS", + "baseMinSize": "10", + "quoteMinSize": "0.001", + "baseMaxSize": "10000000000", + "quoteMaxSize": "99999999", + "baseIncrement": "0.0001", + "quoteIncrement": "0.00001", + "priceIncrement": "0.00001", + "priceLimitRate": "0.1", + "minFunds": "0.1", + "isMarginEnabled": true, + "enableTrading": true + }, + { + "symbol": "XLM-USDT", + "name": "XLM-USDT", + "baseCurrency": "XLM", + "quoteCurrency": "USDT", + "feeCurrency": "USDT", + "market": "USDS", + "baseMinSize": "0.1", + "quoteMinSize": "0.01", + "baseMaxSize": "10000000000", + "quoteMaxSize": "99999999", + "baseIncrement": "0.0001", + "quoteIncrement": "0.000001", + "priceIncrement": "0.000001", + "priceLimitRate": "0.1", + "minFunds": "0.1", + "isMarginEnabled": true, + "enableTrading": true + } + ] + """ + params = {} + if kwargs: + params.update(kwargs) + return await self._request('GET', '/api/v2/symbols', params=params) + + async def get_currency_detail_v3(self, currency,chain=None): + """ + Get Currency Detail + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-currency-detail + """ + params = {} + if chain: + params['chain']=chain + return await self._request('GET', f'/api/v3/currencies/{currency}', params=params) diff --git a/kucoin/asyncio/trade/__init__.py b/kucoin/asyncio/trade/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/kucoin/asyncio/trade/trade.py b/kucoin/asyncio/trade/trade.py new file mode 100644 index 0000000..77b42fc --- /dev/null +++ b/kucoin/asyncio/trade/trade.py @@ -0,0 +1,1725 @@ +from kucoin.asyncio.async_request.async_request import KucoinAsyncRestApi + + +class AsyncTradeData(KucoinAsyncRestApi): + + async def create_limit_margin_order(self, symbol, side, size, price, clientOid='', **kwargs): + """ + Place Margin Order + see: https://www.kucoin.com/docs/rest/margin-trading/orders/place-margin-order + :param symbol: a valid trading symbol code (Mandatory) + :type: str + :param side: place direction buy or sell (Mandatory) + :type: str + :param size: amount of base currency to buy or sell (Mandatory) + :type: str + :param price: price per base currency (Mandatory) + :type: str + :param clientOid: Unique order id created by users to identify their orders, e.g. UUID. (Mandatory) + :type: str + :param kwargs: Fill in parameters with reference documents + :return: { + "orderId": "5bd6e9286d99522a52e458de", + "borrowSize":10.2, + "loanApplyId":"600656d9a33ac90009de4f6f" + } + """ + params = { + 'symbol': symbol, + 'size': size, + 'side': side, + 'price': price, + 'type': "limit" + } + if not clientOid: + clientOid = self.return_unique_id + params['clientOid'] = clientOid + if kwargs: + params.update(kwargs) + + return await self._request('POST', '/api/v1/margin/order', params=params) + + async def create_market_margin_order(self, symbol, side, clientOid='', **kwargs): + """ + Place Margin Order + see: https://www.kucoin.com/docs/rest/margin-trading/orders/place-margin-order + :param symbol: a valid trading symbol code (Mandatory) + :type: str + :param side: place direction buy or sell (Mandatory) + :type: str + :param clientOid: Unique order id created by users to identify their orders, e.g. UUID. (Mandatory) + :type: str + :param kwargs: Fill in parameters with reference documents + :return: { + "orderId": "5bd6e9286d99522a52e458de", + "borrowSize":10.2, + "loanApplyId":"600656d9a33ac90009de4f6f" + } + """ + params = { + 'symbol': symbol, + 'side': side, + 'type': "market" + } + if not clientOid: + clientOid = self.return_unique_id + params['clientOid'] = clientOid + if kwargs: + params.update(kwargs) + + return await self._request('POST', '/api/v1/margin/order', params=params) + + async def place_margin_order_test(self, symbol, side, type,clientOid='', **kwargs): + """ + Place Margin Order Test + https://www.kucoin.com/docs/rest/margin-trading/orders/place-margin-order-test + :param symbol: a valid trading symbol code (Mandatory) + :type: str + :param side: place direction buy or sell (Mandatory) + :type: str + :param clientOid: Unique order id created by users to identify their orders, e.g. UUID. (Mandatory) + :type: str + :param kwargs: Fill in parameters with reference documents + :return: { + "orderId": "5bd6e9286d99522a52e458de", + "borrowSize":10.2, + "loanApplyId":"600656d9a33ac90009de4f6f" + } + """ + params = { + 'symbol': symbol, + 'side': side, + 'type': type + } + if not clientOid: + clientOid = self.return_unique_id + params['clientOid'] = clientOid + if kwargs: + params.update(kwargs) + + return await self._request('POST', '/api/v1/margin/order/test', params=params) + + + async def create_limit_order(self, symbol, side, size, price, clientOid='', **kwargs): + """ + Place Order + https://www.kucoin.com/docs/rest/spot-trading/orders/place-order + :param symbol: a valid trading symbol code (Mandatory) + :type: str + :param side: place direction buy or sell (Mandatory) + :type: str + :param size: amount of base currency to buy or sell (Mandatory) + :type: str + :param price: price per base currency (Mandatory) + :type: str + :param clientOid: Unique order id created by users to identify their orders, e.g. UUID. (Mandatory) + :type: str + :param kwargs: Fill in parameters with reference documents + :return: {'orderId': '5d9ee461f24b80689797fd04'} + """ + params = { + 'symbol': symbol, + 'size': size, + 'side': side, + 'price': price, + 'type': "limit" + } + if not clientOid: + clientOid = self.return_unique_id + params['clientOid'] = clientOid + if kwargs: + params.update(kwargs) + + return await self._request('POST', '/api/v1/orders', params=params) + + + + async def create_limit_stop_order(self, symbol, side, size, price, stopPrice, clientOid="", **kwargs): + params = { + 'symbol': symbol, + 'size': size, + 'side': side, + 'price': price, + 'stopPrice': stopPrice, + 'type': "limit" + } + if not clientOid: + clientOid = self.return_unique_id + params['clientOid'] = clientOid + if kwargs: + params.update(kwargs) + + return await self._request('POST', '/api/v1/stop-order', params=params) + + async def create_market_stop_order(self, symbol, side, stopPrice, size="", funds="", clientOid="", **kwargs): + params = { + 'symbol': symbol, + 'side': side, + 'stopPrice': stopPrice, + 'type': "market" + + } + if not clientOid: + clientOid = self.return_unique_id + params['clientOid'] = clientOid + if size: + params['size'] = size + elif funds: + params['funds'] = funds + else: + raise Exception('Funds or size') + + if kwargs: + params.update(kwargs) + + return await self._request('POST', '/api/v1/stop-order', params=params) + + async def create_market_order(self, symbol, side, clientOid='', size=None,funds=None,**kwargs): + """ + Place Order + https://www.kucoin.com/docs/rest/spot-trading/orders/place-order + :param symbol: a valid trading symbol code (Mandatory) + :type: str + :param side: place direction buy or sell (Mandatory) + :type: str + :param clientOid: Unique order id created by users to identify their orders, e.g. UUID. (Mandatory) + :type: str + :param kwargs: Fill in parameters with reference documents + :return: {'orderId': '5d9ee461f24b80689797fd04'} + """ + params = { + 'symbol': symbol, + 'side': side, + 'type': "market" + } + if size: + params['size']=size + elif funds: + params['funds']=funds + if not clientOid: + clientOid = self.return_unique_id + params['clientOid'] = clientOid + if kwargs: + params.update(kwargs) + + return await self._request('POST', '/api/v1/orders', params=params) + + + async def place_order_test(self, symbol, side,type, clientOid='', **kwargs): + """ + Place Order Test + https://www.kucoin.com/docs/rest/spot-trading/orders/place-order-test + """ + params = { + 'symbol': symbol, + 'side': side, + 'type': type + } + if not clientOid: + clientOid = self.return_unique_id + params['clientOid'] = clientOid + if kwargs: + params.update(kwargs) + + return await self._request('POST', '/api/v1/orders/test', params=params) + + + async def create_bulk_orders(self, symbol, orderList): + """ + https://docs.kucoin.com/#place-bulk-orders + :param symbol: a valid trading symbol code. + :type: str + :param orderList: order list + :type: list + :return: + { + "data": [ + { + "symbol": "KCS-USDT", + "type": "limit", + "side": "buy", + "price": "0.01", + "size": "0.01", + "funds": null, + "stp": "", + "stop": "", + "stopPrice": null, + "timeInForce": "GTC", + "cancelAfter": 0, + "postOnly": false, + "hidden": false, + "iceberge": false, + "iceberg": false, + "visibleSize": null, + "channel": "API", + "id": "611a6a309281bc000674d3c0", + "status": "success", + "failMsg": null, + "clientOid": "552a8a0b7cb04354be8266f0e202e7e9" + }, + { + "symbol": "KCS-USDT", + "type": "limit", + "side": "buy", + "price": "0.01", + "size": "0.01", + "funds": null, + "stp": "", + "stop": "", + "stopPrice": null, + "timeInForce": "GTC", + "cancelAfter": 0, + "postOnly": false, + "hidden": false, + "iceberge": false, + "iceberg": false, + "visibleSize": null, + "channel": "API", + "id": "611a6a309281bc000674d3c1", + "status": "success", + "failMsg": null, + "clientOid": "bd1e95e705724f33b508ed270888a4a9" + } + ] + } + """ + params = { + 'symbol': symbol, + 'orderList': orderList, + } + return await self._request('POST', '/api/v1/orders/multi', params=params) + + async def cancel_client_order(self, clientId): + """ + :param orderId: str (Mandatory) + :return:{"cancelledOrderId": "5f311183c9b6d539dc614db3","clientOid": "6d539dc614db3"} + """ + return await self._request('DELETE', f'/api/v1/order/client-order/{clientId}') + + async def cancel_stop_order(self, orderId): + """ + :param orderId: Order ID, unique ID of the order. (Mandatory) + :type: str + :return: + { + "cancelledOrderIds": [ + "5bd6e9286d99522a52e458de" //orderId + ] + } + """ + return await self._request('DELETE', f'/api/v1/stop-order/{orderId}') + + async def cancel_client_stop_order(self, clientOid, symbol=""): + """ + :param orderId: Order ID, unique ID of the order. (Mandatory) + :type: str + :return: + { + "cancelledOrderIds": [ + "5bd6e9286d99522a52e458de" //orderId + ] + } + """ + params = { + "clientOid": clientOid + } + if symbol: + params["symbol"] = symbol + + return await self._request('DELETE', f'/api/v1/stop-order/cancelOrderByClientOid', params=params) + + async def cancel_stop_condition_order(self, symbol="", tradeType="", orderIds=""): + """ + """ + params = {} + if symbol: + params["symbol"] = symbol + if tradeType: + params["tradeType"] = tradeType + if orderIds: + params["orderIds"] = orderIds + + return await self._request('DELETE', f'/api/v1/stop-order/cancel', params=params) + + async def cancel_order(self, orderId): + """ + https://docs.kucoin.com/#cancel-an-order + + :param orderId: Order ID, unique ID of the order. (Mandatory) + :type: str + :return: + { + "cancelledOrderIds": [ + "5bd6e9286d99522a52e458de" //orderId + ] + } + """ + return await self._request('DELETE', '/api/v1/orders/{orderId}'.format(orderId=orderId)) + + async def cancel_all_orders(self, **kwargs): + """ + https://docs.kucoin.com/#cancel-all-orders + :param kwargs: [optional] symbol, tradeType + :return: + { + "cancelledOrderIds": [ + "5c52e11203aa677f33e493fb", //orderId + "5c52e12103aa677f33e493fe", + "5c52e12a03aa677f33e49401", + "5c52e1be03aa677f33e49404", + "5c52e21003aa677f33e49407", + "5c6243cb03aa67580f20bf2f", + "5c62443703aa67580f20bf32", + "5c6265c503aa676fee84129c", + "5c6269e503aa676fee84129f", + "5c626b0803aa676fee8412a2" + ] + } + """ + params = {} + if kwargs: + params.update(kwargs) + return await self._request('DELETE', '/api/v1/orders', params=params) + + async def get_order_list(self, **kwargs): + """ + https://docs.kucoin.com/#list-orders + :param kwargs: [optional] symbol, status, side, type, tradeType, startAt, endAt, currentPage, pageSize and so on + :return: + { + "currentPage": 1, + "pageSize": 1, + "totalNum": 153408, + "totalPage": 153408, + "items": [ + { + "id": "5c35c02703aa673ceec2a168", //orderid + "symbol": "BTC-USDT", //symbol + "opType": "DEAL", // operation type: DEAL + "type": "limit", // order type,e.g. limit,market,stop_limit. + "side": "buy", // transaction direction,include buy and sell + "price": "10", // order price + "size": "2", // order quantity + "funds": "0", // order funds + "dealFunds": "0.166", // deal funds + "dealSize": "2", // deal quantity + "fee": "0", // fee + "feeCurrency": "USDT", // charge fee currency + "stp": "", // self trade prevention,include CN,CO,DC,CB + "stop": "", // stop type + "stopTriggered": false, // stop order is triggered + "stopPrice": "0", // stop price + "timeInForce": "GTC", // time InForce,include GTC,GTT,IOC,FOK + "postOnly": false, // postOnly + "hidden": false, // hidden order + "iceberg": false, // iceberg order + "visibleSize": "0", // display quantity for iceberg order + "cancelAfter": 0, // cancel orders time,requires timeInForce to be GTT + "channel": "IOS", // order source + "clientOid": "", // user-entered order unique mark + "remark": "", // remark + "tags": "", // tag order source + "isActive": false, // status before unfilled or uncancelled + "cancelExist": false, // order cancellation transaction record + "createdAt": 1547026471000, // create time + "tradeType": "TRADE" + } + ] + } + """ + params = {} + if kwargs: + params.update(kwargs) + + return await self._request('GET', '/api/v1/orders', params=params) + + async def get_recent_orders(self): + """ + https://docs.kucoin.com/#recent-orders + :return: + { + "currentPage": 1, + "pageSize": 1, + "totalNum": 153408, + "totalPage": 153408, + "items": [ + { + "id": "5c35c02703aa673ceec2a168", + "symbol": "BTC-USDT", + "opType": "DEAL", + "type": "limit", + "side": "buy", + "price": "10", + "size": "2", + "funds": "0", + "dealFunds": "0.166", + "dealSize": "2", + "fee": "0", + "feeCurrency": "USDT", + "stp": "", + "stop": "", + "stopTriggered": false, + "stopPrice": "0", + "timeInForce": "GTC", + "postOnly": false, + "hidden": false, + "iceberg": false, + "visibleSize": "0", + "cancelAfter": 0, + "channel": "IOS", + "clientOid": "", + "remark": "", + "tags": "", + "isActive": false, + "cancelExist": false, + "createdAt": 1547026471000, + "tradeType": "TRADE" + } + ] + } + """ + + return await self._request('GET', '/api/v1/limit/orders') + + async def get_order_details(self, orderId): + """ + https://docs.kucoin.com/#get-an-order + :param orderId: Order ID, unique identifier of an order, obtained via the List orders. (Mandatory) + :return: + { + "id": "5c35c02703aa673ceec2a168", + "symbol": "BTC-USDT", + "opType": "DEAL", + "type": "limit", + "side": "buy", + "price": "10", + "size": "2", + "funds": "0", + "dealFunds": "0.166", + "dealSize": "2", + "fee": "0", + "feeCurrency": "USDT", + "stp": "", + "stop": "", + "stopTriggered": false, + "stopPrice": "0", + "timeInForce": "GTC", + "postOnly": false, + "hidden": false, + "iceberg": false, + "visibleSize": "0", + "cancelAfter": 0, + "channel": "IOS", + "clientOid": "", + "remark": "", + "tags": "", + "isActive": false, + "cancelExist": false, + "createdAt": 1547026471000, + "tradeType": "TRADE" + } + """ + return await self._request('GET', '/api/v1/orders/{orderId}'.format(orderId=orderId)) + + async def get_all_stop_order_details(self, **kwargs): + """ + :param orderId: Order ID, unique identifier of an order, obtained via the List orders. (Mandatory) + :return: + { + "id": "5c35c02703aa673ceec2a168", + "symbol": "BTC-USDT", + "opType": "DEAL", + "type": "limit", + "side": "buy", + "price": "10", + "size": "2", + "funds": "0", + "dealFunds": "0.166", + "dealSize": "2", + "fee": "0", + "feeCurrency": "USDT", + "stp": "", + "stop": "", + "stopTriggered": false, + "stopPrice": "0", + "timeInForce": "GTC", + "postOnly": false, + "hidden": false, + "iceberg": false, + "visibleSize": "0", + "cancelAfter": 0, + "channel": "IOS", + "clientOid": "", + "remark": "", + "tags": "", + "isActive": false, + "cancelExist": false, + "createdAt": 1547026471000, + "tradeType": "TRADE" + } + """ + params = {} + if kwargs: + params.update(kwargs) + return await self._request('GET', f'/api/v1/stop-order', params=params) + + async def get_stop_order_details(self, orderId): + """ + :param orderId: Order ID, unique identifier of an order, obtained via the List orders. (Mandatory) + :return: + { + "id": "5c35c02703aa673ceec2a168", + "symbol": "BTC-USDT", + "opType": "DEAL", + "type": "limit", + "side": "buy", + "price": "10", + "size": "2", + "funds": "0", + "dealFunds": "0.166", + "dealSize": "2", + "fee": "0", + "feeCurrency": "USDT", + "stp": "", + "stop": "", + "stopTriggered": false, + "stopPrice": "0", + "timeInForce": "GTC", + "postOnly": false, + "hidden": false, + "iceberg": false, + "visibleSize": "0", + "cancelAfter": 0, + "channel": "IOS", + "clientOid": "", + "remark": "", + "tags": "", + "isActive": false, + "cancelExist": false, + "createdAt": 1547026471000, + "tradeType": "TRADE" + } + """ + return await self._request('GET', f'/api/v1/stop-order/{orderId}') + + async def get_client_stop_order_details(self, clientOid, symbol=''): + """ + :param orderId: Order ID, unique identifier of an order, obtained via the List orders. (Mandatory) + :return: + { + "id": "5c35c02703aa673ceec2a168", + "symbol": "BTC-USDT", + "opType": "DEAL", + "type": "limit", + "side": "buy", + "price": "10", + "size": "2", + "funds": "0", + "dealFunds": "0.166", + "dealSize": "2", + "fee": "0", + "feeCurrency": "USDT", + "stp": "", + "stop": "", + "stopTriggered": false, + "stopPrice": "0", + "timeInForce": "GTC", + "postOnly": false, + "hidden": false, + "iceberg": false, + "visibleSize": "0", + "cancelAfter": 0, + "channel": "IOS", + "clientOid": "", + "remark": "", + "tags": "", + "isActive": false, + "cancelExist": false, + "createdAt": 1547026471000, + "tradeType": "TRADE" + } + """ + params = { + "clientOid": clientOid + } + if symbol: + params["symbol"] = symbol + + return await self._request('GET', f'/api/v1/stop-order/queryOrderByClientOid', params=params) + + async def get_fill_list(self, tradeType, **kwargs): + """ + https://docs.kucoin.com/#list-fills + :param tradeType: The type of trading (Mandatory) + :param kwargs: [Optional] orderId, symbol, side, type, startAt, endAt, currentPage, pageSize + :return: + { + "currentPage":1, + "pageSize":1, + "totalNum":251915, + "totalPage":251915, + "items":[ + { + "symbol":"BTC-USDT", //symbol + "tradeId":"5c35c02709e4f67d5266954e", //trade id + "orderId":"5c35c02703aa673ceec2a168", //order id + "counterOrderId":"5c1ab46003aa676e487fa8e3", //counter order id + "side":"buy", //transaction direction,include buy and sell + "liquidity":"taker", //include taker and maker + "forceTaker":true, //forced to become taker + "price":"0.083", //order price + "size":"0.8424304", //order quantity + "funds":"0.0699217232", //order funds + "fee":"0", //fee + "feeRate":"0", //fee rate + "feeCurrency":"USDT", // charge fee currency + "stop":"", // stop type + "type":"limit", // order type,e.g. limit,market,stop_limit. + "createdAt":1547026472000, //time + "tradeType": "TRADE" + } + ] + } + """ + params = { + 'tradeType': tradeType + } + if kwargs: + params.update(kwargs) + return await self._request('GET', '/api/v1/fills', params=params) + + async def get_recent_fills(self): + """ + https://docs.kucoin.com/#recent-fills + :return: + [ + { + "counterOrderId":"5db7ee769797cf0008e3beea", + "createdAt":1572335233000, + "fee":"0.946357371456", + "feeCurrency":"USDT", + "feeRate":"0.001", + "forceTaker":true, + "funds":"946.357371456", + "liquidity":"taker", + "orderId":"5db7ee805d53620008dce1ba", + "price":"9466.8", + "side":"buy", + "size":"0.09996592", + "stop":"", + "symbol":"BTC-USDT", + "tradeId":"5db7ee8054c05c0008069e21", + "tradeType":"MARGIN_TRADE", + "type":"market" + }, + { + "counterOrderId":"5db7ee4b5d53620008dcde8e", + "createdAt":1572335207000, + "fee":"0.94625", + "feeCurrency":"USDT", + "feeRate":"0.001", + "forceTaker":true, + "funds":"946.25", + "liquidity":"taker", + "orderId":"5db7ee675d53620008dce01e", + "price":"9462.5", + "side":"sell", + "size":"0.1", + "stop":"", + "symbol":"BTC-USDT", + "tradeId":"5db7ee6754c05c0008069e03", + "tradeType":"MARGIN_TRADE", + "type":"market" + }, + { + "counterOrderId":"5db69aa4688933000aab8114", + "createdAt":1572248229000, + "fee":"1.882148318525", + "feeCurrency":"USDT", + "feeRate":"0.001", + "forceTaker":false, + "funds":"1882.148318525", + "liquidity":"maker", + "orderId":"5db69a9c4e6d020008f03275", + "price":"9354.5", + "side":"sell", + "size":"0.20120245", + "stop":"", + "symbol":"BTC-USDT", + "tradeId":"5db69aa477d8de0008c1efac", + "tradeType":"MARGIN_TRADE", + "type":"limit" + } + ] + """ + return await self._request('GET', '/api/v1/limit/fills') + + async def get_client_order_details(self, clientOid): + """ + https://docs.kucoin.com/#recent-fills + :param clientOid: Unique order id created by users to identify their orders + :return: + { + "id": "61149d589281bc00064a9ee0", + "symbol": "KCS-USDT", + "opType": "DEAL", + "type": "limit", + "side": "buy", + "price": "0.001", + "size": "0.01", + "funds": "0", + "dealFunds": "0", + "dealSize": "0", + "fee": "0", + "feeCurrency": "USDT", + "stp": "", + "stop": "", + "stopTriggered": false, + "stopPrice": "0", + "timeInForce": "GTC", + "postOnly": false, + "hidden": false, + "iceberg": false, + "visibleSize": "0", + "cancelAfter": 0, + "channel": "API", + "clientOid": "03cd879961b64429b0e0149f311ce59f", + "remark": null, + "tags": null, + "isActive": false, + "cancelExist": true, + "createdAt": 1628740952556, + "tradeType": "MARGIN_TRADE" + } + """ + return await self._request('GET', f'/api/v1/order/client-order/{clientOid}') + + async def create_limit_hf_order(self, symbol, side, size, price, clientOid='', **kwargs): + """ + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/place-hf-order + :param symbol: a valid trading symbol code (Mandatory) + :type: str + :param side: place direction buy or sell (Mandatory) + :type: str + :param size: amount of base currency to buy or sell (Mandatory) + :type: str + :param price: price per base currency (Mandatory) + :type: str + :param clientOid: Unique order id created by users to identify their orders, e.g. UUID. (Mandatory) + :type: str + :param kwargs: Fill in parameters with reference documents + :return: {'orderId': '5d9ee461f24b80689797fd04'} + """ + params = { + 'symbol': symbol, + 'size': size, + 'side': side, + 'price': price, + 'type': "limit" + } + if not clientOid: + clientOid = self.return_unique_id + params['clientOid'] = clientOid + if kwargs: + params.update(kwargs) + + return await self._request('POST', '/api/v1/hf/orders', params=params) + + async def create_hf_market_order(self, symbol, side, clientOid='', **kwargs): + """ + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/place-hf-order + :param symbol: a valid trading symbol code (Mandatory) + :type: str + :param side: place direction buy or sell (Mandatory) + :type: str + :param clientOid: Unique order id created by users to identify their orders, e.g. UUID. (Mandatory) + :type: str + :param kwargs: Fill in parameters with reference documents + :return: {'orderId': '5d9ee461f24b80689797fd04'} + """ + params = { + 'symbol': symbol, + 'side': side, + 'type': "market" + } + if not clientOid: + clientOid = self.return_unique_id + params['clientOid'] = clientOid + if kwargs: + params.update(kwargs) + + return await self._request('POST', '/api/v1/hf/orders', params=params) + + async def place_hf_order_test(self, symbol, side, size, price,type, clientOid='', **kwargs): + """ + Place HF order Test + see: https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/place-hf-order-test + """ + params = { + 'symbol': symbol, + 'size': size, + 'side': side, + 'price': price, + 'type': type + } + if not clientOid: + clientOid = self.return_unique_id + params['clientOid'] = clientOid + if kwargs: + params.update(kwargs) + return await self._request('POST', '/api/v1/hf/orders/test', params=params) + + + async def sync_create_limit_hf_order(self, symbol, side, size, price, clientOid='', **kwargs): + """ + https://docs.kucoin.com/spot-hf/#sync-place-hf-order + :param symbol: a valid trading symbol code (Mandatory) + :type: str + :param side: place direction buy or sell (Mandatory) + :type: str + :param size: amount of base currency to buy or sell (Mandatory) + :type: str + :param price: price per base currency (Mandatory) + :type: str + :param clientOid: Unique order id created by users to identify their orders, e.g. UUID. (Mandatory) + :type: str + :param kwargs: Fill in parameters with reference documents + :return: + { + "orderId": "6d539dc614db3", + "orderTime": "1507725176595",//order time + "originSize": "10.01", + "dealSize": "2.01", + "remainSize": "8", + "canceledSize": "0", + "status": "open", //open: the order is active: the order has been completed + "matchTime": "1507725176595" //begin match time + } + """ + params = { + 'symbol': symbol, + 'size': size, + 'side': side, + 'price': price, + 'type': "limit" + } + if not clientOid: + clientOid = self.return_unique_id + params['clientOid'] = clientOid + if kwargs: + params.update(kwargs) + + return await self._request('POST', '/api/v1/hf/orders/sync', params=params) + + async def sync_create_hf_market_order(self, symbol, side, clientOid='', **kwargs): + """ + https://docs.kucoin.com/spot-hf/#sync-place-hf-order + :param symbol: a valid trading symbol code (Mandatory) + :type: str + :param side: place direction buy or sell (Mandatory) + :type: str + :param clientOid: Unique order id created by users to identify their orders, e.g. UUID. (Mandatory) + :type: str + :param kwargs: Fill in parameters with reference documents + :return: + { + "orderId": "6d539dc614db3", + "orderTime": "1507725176595",//order time + "originSize": "10.01", + "dealSize": "2.01", + "remainSize": "8", + "canceledSize": "0", + "status": "open", //open: the order is active: the order has been completed + "matchTime": "1507725176595" //begin match time + } + """ + params = { + 'symbol': symbol, + 'side': side, + 'type': "market" + } + if not clientOid: + clientOid = self.return_unique_id + params['clientOid'] = clientOid + if kwargs: + params.update(kwargs) + + return await self._request('POST', '/api/v1/hf/orders/sync', params=params) + + async def multi_create_hf_order(self, orderList): + """ + https://docs.kucoin.com/spot-hf/#place-multiple-hf-orders + :param orderList: order list + :type: list + :return: + [ + { + "orderId": "641d669c9ca34800017a2a3c", + "success": true + }, + { + "orderId": "641d669c9ca34800017a2a45", + "success": true + } + ] + """ + params = { + 'orderList': orderList + } + return await self._request('POST', '/api/v1/hf/orders/multi', params=params) + + async def sync_multi_create_hf_order(self, orderList): + """ + https://docs.kucoin.com/spot-hf/#sync-place-multiple-hf-orders + :param orderList: order list + :type: list + :return: + [ + { + "orderId": "641d67ea162d47000160bfb8", + "orderTime": 1679648746796, + "originSize": "1", + "dealSize": "0", + "remainSize": "1", + "canceledSize": "0", + "status": "open", + "matchTime": 1679648746443, + "success": true + }, + { + "orderId": "641d67eb162d47000160bfc0", + "orderTime": 1679648747369, + "originSize": "1", + "dealSize": "0", + "remainSize": "1", + "canceledSize": "0", + "status": "open", + "matchTime": 1679648746644, + "success": true + } + ] + """ + params = { + 'orderList': orderList + } + return await self._request('POST', '/api/v1/hf/orders/multi/sync', params=params) + + async def modify_hf_order(self, symbol, clientOid='', **kwargs): + """ + https://docs.kucoin.com/spot-hf/#modify-order + :param symbol: a valid trading symbol code (Mandatory) + :type: str + :param clientOid: Unique order id created by users to identify their orders, e.g. UUID. (Mandatory) + :type: str + :param kwargs: Fill in parameters with reference documents + :return: + { + "newOrderId": "6d539dc614db3" + } + """ + params = { + 'symbol': symbol + } + if not clientOid: + clientOid = self.return_unique_id + params['clientOid'] = clientOid + if kwargs: + params.update(kwargs) + + return await self._request('POST', '/api/v1/hf/orders/alter', params=params) + + async def cancel_hf_order_by_order_id(self, symbol, orderId): + """ + https://docs.kucoin.com/spot-hf/#cancel-orders-by-orderid + :param symbol: a valid trading symbol code (Mandatory) + :type: str + :param orderId: Path parameter,Order Id unique identifier (Mandatory) + :type: str + :return: + { + "orderId": "6d539dc614db3" + } + """ + params = { + 'symbol': symbol + } + return await self._request('DELETE', '/api/v1/hf/orders/{orderId}'.format(orderId=orderId), params=params) + + async def sync_cancel_hf_order_by_order_id(self, symbol, orderId): + """ + https://docs.kucoin.com/spot-hf/#sync-cancel-orders-by-orderid + :param symbol: a valid trading symbol code (Mandatory) + :type: str + :param orderId: Path parameter,Order Id unique identifier (Mandatory) + :type: str + :return: + { + "orderId": "641d67ea162d47000160bfb8", + "originSize": "1", + "dealSize": "0", + "remainSize": "1", + "canceledSize": "0", + "status": "done" + } + """ + params = { + 'symbol': symbol + } + return await self._request('DELETE', '/api/v1/hf/orders/sync/{orderId}'.format(orderId=orderId), params=params) + + async def cancel_hf_order_by_client_id(self, symbol, clientOid): + """ + https://docs.kucoin.com/spot-hf/#cancel-order-by-clientoid + :param symbol: a valid trading symbol code (Mandatory) + :type: str + :param clientOid: Path parameter,an identifier created by the (Mandatory) + :type: str + :return: + { + "clientOid": "6d539dc614db3" + } + """ + params = { + 'symbol': symbol + } + return await self._request('DELETE', '/api/v1/hf/orders/client-order/{clientOid}'.format(clientOid=clientOid), params=params) + + async def sync_cancel_hf_order_by_client_id(self, symbol, clientOid): + """ + https://docs.kucoin.com/spot-hf/#sync-cancel-orders-by-clientoid + :param symbol: a valid trading symbol code (Mandatory) + :type: str + :param clientOid: Path parameter,an identifier created by the (Mandatory) + :type: str + :return: + { + "orderId": "641d67ea162d47000160bfb8", + "originSize": "1", + "dealSize": "0", + "remainSize": "1", + "canceledSize": "0", + "status": "done" + } + """ + params = { + 'symbol': symbol + } + return await self._request('DELETE', '/api/v1/hf/orders/sync/client-order/{clientOid}'.format(clientOid=clientOid), params=params) + + async def cancel_hf_order_specified_number_by_order_id(self, symbol, orderId, cancelSize): + """ + https://docs.kucoin.com/spot-hf/#cancel-specified-number-of-orders-by-orderid + :param symbol: a valid trading symbol code (Mandatory) + :type: str + :param orderId: Order id of the cancelled order + :type: str + :param cancelSize: canceled size + :type: str + :return: + { + "orderId": "6d539dc614db3", + "cancelSize": "10.01" + } + """ + params = { + 'symbol': symbol, + 'cancelSize': cancelSize + } + return await self._request('DELETE', '/api/v1/hf/orders/cancel/{orderId}'.format(orderId=orderId), params=params) + + async def cancel_all_hf_orders(self, symbol): + """ + https://docs.kucoin.com/spot-hf/#cancel-all-hf-orders-by-symbol + :param symbol: a valid trading symbol code (Mandatory) + :type: str + :return: "success" + """ + params = { + 'symbol': symbol + } + return await self._request('DELETE', '/api/v1/hf/orders', params=params) + + async def get_active_hf_orders(self, symbol): + """ + https://docs.kucoin.com/spot-hf/#obtain-list-of-active-hf-orders + :param symbol: a valid trading symbol code (Mandatory) + :type: str + :return: + [ + "id": "5c35c02703aa673ceec2a168", + "symbol": "BTC-USDT", + "opType": "DEAL", + "type": "limit", + "side": "buy", + "price": "10", + "size": "2", + "funds": "0", + "dealFunds": "0.166", + "dealSize": "2", + "fee": "0", + "feeCurrency": "USDT", + "stp": "", + "timeInForce": "GTC", + "postOnly": false, + "hidden": false, + "iceberg": false, + "visibleSize": "0", + "cancelAfter": 0, + "channel": "IOS", + "clientOid": "", + "remark": "", + "tags": "", + "active": true, + "inOrderBook": true, + "cancelExist": false, + "createdAt": 1547026471000, + "lastUpdatedAt": 1547026471001, + "tradeType": "TRADE", + "cancelledSize": "0", + "cancelledFunds": "0", + "remainSize": "0", + "remainFunds": "0" + } + ] + """ + params = { + 'symbol': symbol + } + return await self._request('GET', '/api/v1/hf/orders/active', params=params) + + async def get_symbol_with_active_hf_orders(self): + """ + https://docs.kucoin.com/spot-hf/#obtain-list-of-symbol-with-active-hf-orders + :return: + { + "symbols": ["BTC-USDT"] + } + """ + return await self._request('GET', '/api/v1/hf/orders/active/symbols') + + async def get_filled_hf_order(self, symbol, **kwargs): + """ + https://docs.kucoin.com/spot-hf/#obtain-list-of-filled-hf-orders + :param symbol: a valid trading symbol code (Mandatory) + :type: str + :param kwargs: Fill in parameters with reference documents + :return: + { + "lastId":2682265600, + "items":[ + { + "id":"63074a5a27ecbe0001e1f3ba", + "symbol":"CSP-USDT", + "opType":"DEAL", + "type":"limit", + "side":"sell", + "price":"0.1", + "size":"0.1", + "funds":"0.01", + "dealSize":"0", + "dealFunds":"0", + "fee":"0", + "feeCurrency":"USDT", + "stp":"", + "timeInForce":"GTC", + "postOnly":false, + "hidden":false, + "iceberg":false, + "visibleSize":"0", + "cancelAfter":0, + "channel":"API", + "clientOid":"", + "remark":"", + "tags":"", + "cancelExist":true, + "createdAt":1661422170924, + "lastUpdatedAt":1661422196926, + "tradeType":"TRADE", + "inOrderBook":false, + "active":false, + "cancelledSize": "0", + "cancelledFunds": "0", + "remainSize": "0", + "remainFunds": "0" + } + ] + } + """ + params = { + 'symbol': symbol + } + if kwargs: + params.update(kwargs) + + return await self._request('GET', '/api/v1/hf/orders/done', params=params) + + async def get_single_hf_order(self, symbol, orderId): + """ + https://docs.kucoin.com/spot-hf/#details-of-a-single-hf-order + :param symbol: a valid trading symbol code (Mandatory) + :type: str + :param orderId: Order id of the cancelled order + :type: str + :return: + { + "id": "5f3113a1c9b6d539dc614dc6", + "symbol": "KCS-BTC", + "opType": "DEAL", + "type": "limit", + "side": "buy", + "price": "0.00001", + "size": "1", + "funds": "0", + "dealFunds": "0", + "dealSize": "0", + "fee": "0", + "feeCurrency": "BTC", + "stp": "", + "timeInForce": "GTC", + "postOnly": false, + "hidden": false, + "iceberg": false, + "visibleSize": "0", + "cancelAfter": 0, + "channel": "API", + "clientOid": "6d539dc614db312", + "remark": "", + "tags": "", + "active": true, + "inOrderBook": false, + "cancelExist": false, + "createdAt": 1547026471000, + "lastUpdatedAt": 1547026471001, + "tradeType": "TRADE", + "cancelledSize": "0", + "cancelledFunds": "0", + "remainSize": "0", + "remainFunds": "0" + } + """ + params = { + 'symbol': symbol + } + return await self._request('GET', '/api/v1/hf/orders/{orderId}'.format(orderId=orderId), params=params) + + async def get_single_hf_order_by_client_oid(self, symbol, clientOid): + """ + https://docs.kucoin.com/spot-hf/#obtain-details-of-a-single-hf-order-using-clientoid + :param symbol: a valid trading symbol code (Mandatory) + :type: str + :param clientOid: Path parameter,an identifier created by the client + :type: str + :return: + { + "id": "5f3113a1c9b6d539dc614dc6", + "symbol": "KCS-BTC", + "opType": "DEAL", + "type": "limit", + "side": "buy", + "price": "0.00001", + "size": "1", + "funds": "0", + "dealFunds": "0", + "dealSize": "0", + "fee": "0", + "feeCurrency": "BTC", + "stp": "", + "timeInForce": "GTC", + "postOnly": false, + "hidden": false, + "iceberg": false, + "visibleSize": "0", + "cancelAfter": 0, + "channel": "API", + "clientOid": "6d539dc614db312", + "remark": "", + "tags": "", + "active": true, + "inOrderBook": false, + "cancelExist": false, + "createdAt": 1547026471000, + "lastUpdatedAt": 1547026471001, + "tradeType": "TRADE", + "cancelledSize": "0", + "cancelledFunds": "0", + "remainSize": "0", + "remainFunds": "0" + } + """ + params = { + 'symbol': symbol + } + return await self._request('GET', '/api/v1/hf/orders/client-order/{clientOid}'.format(clientOid=clientOid), params=params) + + async def set_hf_auto_cancel(self, timeout, **kwargs): + """ + https://docs.kucoin.com/spot-hf/#hf-auto-cancel-setting + :param timeout: Auto cancel order trigger setting time, the unit is second. + range: timeout=-1 (meaning unset) or 5 <= timeout <= 86400. For example, + timeout=5 means that the order will be automatically canceled if no user request is received for more than 5 seconds. + When this parameter is changed, the previous setting will be overwritten. (Mandatory) + :param kwargs: Fill in parameters with reference documents + :return: + { + "currentTime": 1682010526, + "triggerTime": 1682010531 + } + """ + params = { + 'timeout': timeout + } + if kwargs: + params.update(kwargs) + + return await self._request('POST', '/api/v1/hf/orders/dead-cancel-all', params=params) + + async def query_hf_auto_cancel_setting(self): + """ + https://docs.kucoin.com/spot-hf/#hf-auto-cancel-order-setting-query + :return: + { + "timeout": 5, + "symbols": "BTC-USDT", + "currentTime": 1682010526, + "triggerTime": 1682010531 + } + """ + return await self._request('GET', '/api/v1/hf/orders/dead-cancel-all/query') + + async def get_hf_transaction_records(self, symbol, **kwargs): + """ + https://docs.kucoin.com/spot-hf/#hf-transaction-records + :param symbol: Only returns order information for the specified trading pair + :param kwargs: Fill in parameters with reference documents + :return: + { + "items":[ + { + "id":2678765568, + "symbol":"BTC-ETC", + "tradeId":616179312641, + "orderId":"6306cf6e27ecbe0001e1e03a", + "counterOrderId":"6306cf4027ecbe0001e1df4d", + "side":"buy", + "liquidity":"taker", + "forceTaker":false, + "price":"1", + "size":"1", + "funds":"1", + "fee":"0.00021", + "feeRate":"0.00021", + "feeCurrency":"USDT", + "stop":"", + "tradeType":"TRADE", + "type":"limit", + "createdAt":1661390702919 + } + ], + "lastId":2678765568 + } + """ + params = { + 'symbol': symbol + } + if kwargs: + params.update(kwargs) + + return await self._request('GET', '/api/v1/hf/fills', params=params) + + async def create_oco_order(self, symbol, side, price, stopPrice, size, limitPrice, clientOid="", remark=None): + """ + Place Order + Do not include extra spaces in JSON strings in request body. + Limitation + The maximum untriggered stop orders for a single trading pair in one account is 20. + https://www.kucoin.com/docs/rest/spot-trading/oco-order/place-order + + :param symbol: symbol, such as, ETH-BTC + :param side: buy or sell + :param price: Specify price for currency + :param stopPrice: trigger price + :param size: Specify quantity for currency + :param limitPrice: The limit order price after take-profit and stop-loss are triggered + :param clientOid: Client Order Id,unique identifier created by the user, the use of UUID is recommended, e.g. UUID, with a maximum length of 128 bits + :param remark: Order placement remarks, length cannot exceed 100 characters (UTF-8) + :return: + { + "orderId": "6572fdx65723280007deb5ex" + } + """ + params = { + 'symbol': symbol, + 'side': side, + 'price': price, + 'size': size, + 'stopPrice': stopPrice, + 'limitPrice': limitPrice, + 'tradeType': 'TRADE', + } + if not clientOid: + clientOid = self.return_unique_id + params['clientOid'] = clientOid + if remark: + params['remark'] = remark + + return await self._request('POST', '/api/v3/oco/order', params=params) + + + async def get_hf_completed_orders(self, symbol, **kwargs): + """ + Get HF Completed order list + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/get-hf-completed-order-list + Param Type Mandatory Description + :param symbol String Yes Only returns order information for the specified trading pair + :param kwargs Reference api documentation + """ + params = { + 'symbol': symbol + } + if kwargs: + params.update(kwargs) + + return await self._request('GET', '/api/v1/hf/orders/done', params=params) + + async def get_hf_filled_list(self, symbol, **kwargs): + """ + Get HF Filled List + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/get-hf-filled-list + :param symbol: Only returns order information for the specified trading pair + :param kwargs: Fill in parameters with reference documents + :return: + { + "items":[ + { + "id":2678765568, + "symbol":"BTC-ETC", + "tradeId":616179312641, + "orderId":"6306cf6e27ecbe0001e1e03a", + "counterOrderId":"6306cf4027ecbe0001e1df4d", + "side":"buy", + "liquidity":"taker", + "forceTaker":false, + "price":"1", + "size":"1", + "funds":"1", + "fee":"0.00021", + "feeRate":"0.00021", + "feeCurrency":"USDT", + "stop":"", + "tradeType":"TRADE", + "type":"limit", + "createdAt":1661390702919 + } + ], + "lastId":2678765568 + } + """ + params = { + 'symbol': symbol + } + if kwargs: + params.update(kwargs) + + return await self._request('GET', '/api/v1/hf/fills', params=params) + async def cancel_oco_order(self, orderId): + """ + Cancel Order by orderId + Request via this endpoint to cancel a single oco order previously placed. + You will receive cancelledOrderIds field once the system has received the cancellation request. The cancellation request will be processed by the matching engine in sequence. To know if the request is processed (successfully or not), you may check the order status or the update message from the pushes. + https://www.kucoin.com/docs/rest/spot-trading/oco-order/cancel-order-by-orderid + :param orderId: Path parameter, Order Id unique identifier + :type: str + :return: + { + "cancelledOrderIds": [ //List of two order IDs related to the canceled OCO order + "vs9hqpbivnbpkfdj003qlxxx", + "vs9hqpbivnbpkfdj003qlxxx" + ] + } + """ + return await self._request('DELETE', f'/api/v3/oco/order/{orderId}') + + async def cancel_oco_order_by_clientOid(self, clientOid): + """ + Cancel Order by clientOid + https://www.kucoin.com/docs/rest/spot-trading/oco-order/cancel-order-by-clientoid + :param clientOid: Path parameter,Unique order id created by users to identify their orders + :return: + { + "cancelledOrderIds": [ //List of two order IDs related to the canceled OCO order + "vs9hqpbivnbpkfdj003qlxxx", + "vs9hqpbivnbpkfdj003qlxxx" + ] + } + """ + return await self._request('DELETE', f'/api/v3/oco/client-order/{clientOid}') + + async def cancel_all_oco_orders(self, symbol=None, orderIds=None): + """ + Cancel Multiple Orders + This interface can batch cancel OCO orders through orderIds. + https://www.kucoin.com/docs/rest/spot-trading/oco-order/cancel-multiple-orders + + :param symbol: trading pair. If not passed, the oco orders of all symbols will be canceled by default. + :param orderIds: Specify the order number, there can be multiple orders, separated by commas. If not passed, all oco orders will be canceled by default. + :return: + { + "cancelledOrderIds": [ + "vs9hqpbivcq5dcu2003o19ta", + "vs9hqpbivcq5dcu2003o19tb", + "vs9hqpbive99kfdj003ql1j2", + "vs9hqpbive99kfdj003ql1j3" + ] + } + """ + params = {} + if symbol: + params['symbol']=symbol + if orderIds: + params['orderIds']=orderIds + return await self._request('DELETE', '/api/v3/oco/orders', params=params) + + async def get_oco_order_by_orderId(self, orderId): + """ + Get Order Info by orderId + Request via this interface to get a oco order information via the order ID. + https://www.kucoin.com/docs/rest/spot-trading/oco-order/get-order-info-by-orderid + :param orderId: Path parameter, Order Id unique identifier + :return: + { + "orderId": "6572fdd65723280007deb5e0", + "symbol": "FRM-USDT", + "clientOid": "9a05f706a39eff673045b89foco1", + "orderTime": 1702034902724, + "status": "NEW" + } + """ + return await self._request('GET', f'api/v3/oco/order/{orderId}') + + + async def get_oco_order_by_client_oid(self, clientOid): + """ + Get Order Info by clientOid + https://docs.kucoin.com/spot-hf/#obtain-details-of-a-single-hf-order-using-clientoid + :param clientOid: Path parameter,Unique order id created by users to identify their orders + :type: str + :return: + { + "orderId": "6572fdd65723280007deb5e0", + "symbol": "FRM-USDT", + "clientOid": "9a05f706a39eff673045b89foco1", + "orderTime": 1702034902724, + "status": "NEW" + } + """ + return await self._request('GET', f'/api/v3/oco/client-order/{clientOid}') + + async def get_oco_orders(self,pageSize,currentPage,symbol=None,startAt=None,endAt=None,orderIds=None): + """ + Get Order List + Request via this endpoint to get your current OCO order list. Items are paginated and sorted to show the latest first. See the Pagination section for retrieving additional entries after the first page. + https://www.kucoin.com/docs/rest/spot-trading/oco-order/get-order-list + :param pageSize: Size per page, minimum value 10, maximum value 500 (Mandatory) + :param currentPage: Page number, minimum value 1 (Mandatory) + :param symbol: Only order information for the specified Symbol is returned + :param startAt: Start time (milliseconds) + :param endAt: End time (milliseconds) + :param orderIds: Specify orderId collection, up to 500 orders + :return: + { + "currentPage": 1, + "pageSize": 10, + "totalNum": 4, + "totalPage": 1, + "items": [ + { + "orderId": "6572fdd65723280007deb5e0", + "symbol": "FRM-USDT", + "clientOid": "9a05f706a39eff673045b89foco1", + "orderTime": 1702034902724, + "status": "NEW" + }, + { + "orderId": "6572fbbea24eca0007c8aaa9", + "symbol": "FRM-USDT", + "clientOid": "afe2d9deeba49f5ffee1792aoco1", + "orderTime": 1702034366305, + "status": "NEW" + } + ] + } + """ + params={ + 'pageSize':pageSize, + 'currentPage':currentPage + } + if symbol: + params['symbol']=symbol + if startAt: + params['startAt']=startAt + if endAt: + params['endAt']=endAt + if orderIds: + params['orderIds']=orderIds + + return await self._request('GET', '/api/v3/oco/orders',params=params) + + async def get_oco_order_details(self, orderId): + """ + Get Order Details by orderId + Request via this interface to get a oco order detail via the order ID. + https://www.kucoin.com/docs/rest/spot-trading/oco-order/get-order-details-by-orderid + :param orderId: Path parameter, Order Id unique identifier + :type: str + :return: + { + "orderId": "6572fdd65723280007deb5e0", + "symbol": "FRM-USDT", + "clientOid": "9a05f706a39eff673045b89foco1", + "orderTime": 1702034902724, + "status": "NEW", + "orders": [ + { + "id": "vs9hqpbivnb5e8p8003ttdf1", + "symbol": "FRM-USDT", + "side": "sell", + "price": "1.00000000000000000000", + "stopPrice": "1.00000000000000000000", + "size": "25.00000000000000000000", + "status": "NEW" + }, + { + "id": "vs9hqpbivnb5e8p8003ttdf2", + "symbol": "FRM-USDT", + "side": "sell", + "price": "3.00000000000000000000", + "stopPrice": "0.06000000000000000000", + "size": "25.00000000000000000000", + "status": "NEW" + } + ] + } + """ + return await self._request('GET', f'api/v3/oco/order/details/{orderId}') + + async def cancel_all_hf_orders(self): + """ + Cancel all HF orders + This endpoint can cancel all HF orders for all symbol. + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/cancel-all-hf-orders + + :return: + { + "succeedSymbols": [ + "BTC-USDT", + "ETH-USDT" + ], + "failedSymbols": [ + { + "symbol": "BTC-USDT", + "error": "can't cancel, system timeout" + } + ], + } + """ + return await self._request('DELETE', '/api/v1/hf/orders/cancelAll') diff --git a/kucoin/asyncio/user/__init__.py b/kucoin/asyncio/user/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/kucoin/asyncio/user/user.py b/kucoin/asyncio/user/user.py new file mode 100644 index 0000000..c53f7a0 --- /dev/null +++ b/kucoin/asyncio/user/user.py @@ -0,0 +1,1000 @@ +from kucoin.asyncio.async_request.async_request import KucoinAsyncRestApi + + +class AsyncUserData(KucoinAsyncRestApi): + + async def get_actual_fee(self, symbols): + """ + https://docs.kucoin.top/#actual-fee-rate-of-the-trading-pair + :param symbols: symbols + :type: str + :return: + { + "code": "200000", + "data": [ + { + "symbol": "BTC-USDT", + "takerFeeRate": "0.001", + "makerFeeRate": "0.001" + }, + { + "symbol": "KCS-USDT", + "takerFeeRate": "0.002", + "makerFeeRate": "0.0005" + } + ] + } + """ + params = { + "symbols": symbols + } + return await self._request('GET', '/api/v1/trade-fees', params=params) + + async def get_base_fee(self): + """ + https://docs.kucoin.top/#basic-user-fee + + :return: + { + "code": "200000", + "data": { + "takerFeeRate": "0.001", + "makerFeeRate": "0.001" + } + } + """ + return await self._request('GET', '/api/v1/base-fee') + + async def get_sub_user(self): + """ + https://docs.kucoin.com/#get-user-info-of-all-sub-accounts + + :return: + [{ + "userId": "5cbd31ab9c93e9280cd36a0a", //subUserId + "subName": "kucoin1", + "remarks": "kucoin1" + }, + { + "userId": "5cbd31b89c93e9280cd36a0d", + "subName": "kucoin2", + "remarks": "kucoin2" + } + ] + """ + return await self._request('GET', '/api/v1/sub/user') + + async def create_account(self, account_type, currency): + """ + https://docs.kucoin.com/#create-an-account + :param account_type: Account type (Mandatory) + :type: str + :param currency: Currency (Mandatory) + :type: str + :return: + { + "id": "5bd6e9286d99522a52e458de" //accountId + } + """ + params = { + 'type': account_type, + 'currency': currency + } + return await self._request('POST', '/api/v1/accounts', params=params) + + async def get_account_list(self, currency=None, account_type=None): + """ + https://docs.kucoin.com/#list-accounts + :param currency: Currency (Optional) + :type: str + :param account_type: Account type (Optional) + :type: str + :return: + [{ + "id": "5bd6e9286d99522a52e458de", //accountId + "currency": "BTC", //Currency + "type": "main", //Account type, including main and trade + "balance": "237582.04299", //Total assets of a currency + "available": "237582.032", //Available assets of a currency + "holds": "0.01099". //Hold assets of a currency + }, + { + "id": "5bd6e9216d99522a52e458d6", + "currency": "BTC", + "type": "trade", + "balance": "1234356", + "available": "1234356", + "holds": "0" + }] + """ + params = {} + if currency: + params['currency'] = currency + if account_type: + params['type'] = account_type + return await self._request('GET', '/api/v1/accounts', params=params) + + async def get_account(self, accountId): + """ + https://docs.kucoin.com/#get-an-account + :param accountId: ID of the account (Mandatory) + :type: str + :return: + { + "currency": "KCS", //Currency + "balance": "1000000060.6299", //Total assets of a currency + "available": "1000000060.6299", //Available assets of a currency + "holds": "0". //Hold assets of a currency + } + """ + return await self._request('GET', '/api/v1/accounts/{accountId}'.format(accountId=accountId)) + + async def get_account_ledger(self, **kwargs): + """ + https://docs.kucoin.top/#get-account-ledgers + :param kwargs: [optional] currency, direction, bizType, startAt, endAt, currentPage , pageSize + :return: + { + "currentPage": 1, + "pageSize": 10, + "totalNum": 3, + "totalPage": 1, + "items": [ + { + "id": "5bc7f080b39c5c03486eef8c",//unique key + "currency": "KCS", //Currency + "amount": "0.0998", //Change amount of the funds + "fee": "0", //Deposit or withdrawal fee + "balance": "0", //Total assets of a currency + "bizType": "Withdraw", //business type + "direction": "in", //side, in or out + "createdAt": 1540296039000, //Creation time + "context": { //Business core parameters + + "orderId": "5bc7f080b39c5c03286eef8a", + "txId": "bf848bfb6736780b930e12c68721ea57f8b0484a4af3f30db75c93ecf16905c9" + } + }, + { + "id": "5bc7f080b39c5c03486def8c",//unique key + "currency": "KCS", + "amount": "0.0998", + "fee": "0", + "balance": "0", + "bizType": "Deposit", + "direction": "in", + "createdAt": 1540296039000, + "context": { + + "orderId": "5bc7f080b39c5c03286eef8a", + "txId": "bf848bfb6736780b930e12c68721ea57f8b0484a4af3f30db75c93ecf16905c9" + } + }, + { + "id": "5bc7f080b39c5c03486def8a",//unique key + "currency": "KCS", + "amount": "0.0998", + "fee": "0", + "balance": "0", + "bizType": "trade exchange", + "direction": "in", + "createdAt": 1540296039000, + "context": { + + "tradeId": "5bc7f080b3949c03286eef8a", + "orderId": "5bc7f080b39c5c03286eef8e", + "symbol": "BTC-USD" + } + } + ] + } + """ + params = {} + if kwargs: + params.update(kwargs) + + return await self._request('GET', '/api/v1/accounts/ledgers', params=params) + + async def get_account_hold(self, accountId, **kwargs): + """ + https://docs.kucoin.com/#get-holds + :param accountId: ID of the account. (Mandatory) + :type: str + :param kwargs: [optional] currentPage , pageSize + :return: + { + "currentPage": 1, + "pageSize": 10, + "totalNum": 2, + "totalPage": 1, + "items": [ + { + "currency": "ETH", //Currency + "holdAmount": "5083", //Hold amount of a currency + "bizType": "Withdraw", //business type + "orderId": "5bc7f080b39c5c03286eef8e", // ID of funds freezed order + "createdAt": 1545898567000, //Creation time + "updatedAt": 1545898567000。//update time + }, + { + "currency": "ETH", + "holdAmount": "1452", + "bizType": "Withdraw", + "orderId": "5bc7f518b39c5c033818d62d", + "createdAt": 1545898567000, + "updatedAt": 1545898567000 + } + ] + } + """ + params = {} + if kwargs: + params.update(kwargs) + return await self._request('GET', '/api/v1/accounts/{accountId}/holds'.format(accountId=accountId), params=params) + + async def get_sub_account(self, subUserId): + """ + https://docs.kucoin.com/#get-account-balance-of-a-sub-account + :param subUserId: the user ID of a sub-account. (Mandatory) + :type: str + :return: + { + "subUserId": "5caefba7d9575a0688f83c45", + "subName": "sdfgsdfgsfd", + "mainAccounts": [{ + "currency": "BTC", + "balance": "8", + "available": "8", + "holds": "0", + "baseCurrency": "BTC", + "baseCurrencyPrice": "1", + "baseAmount": "1.1" + }], + "tradeAccounts": [{ + "currency": "BTC", + "balance": "1000", + "available": "1000", + "holds": "0", + "baseCurrency": "BTC", + "baseCurrencyPrice": "1", + "baseAmount": "1.1" + + }], + "marginAccounts": [{ + "currency": "BTC", + "balance": "1.1", + "available": "1.1", + "holds": "0", + "baseCurrency": "BTC", + "baseCurrencyPrice": "1", + "baseAmount": "1.1" + }] + } + """ + return await self._request('GET', '/api/v1/sub-accounts/{subUserId}'.format(subUserId=subUserId)) + + async def get_sub_accounts(self): + """ + https://docs.kucoin.com/#get-the-aggregated-balance-of-all-sub-accounts + :return: + [ + { + "subUserId": "5caefba7d9575a0688f83c45", + "subName": "kucoin1", + "mainAccounts": [{ + "currency": "BTC", + "balance": "6", + "available": "6", + "holds": "0", + "baseCurrency": "BTC", + "baseCurrencyPrice": "1", + "baseAmount": "1.1" + + }], + "tradeAccounts": [{ + "currency": "BTC", + "balance": "1000", + "available": "1000", + "holds": "0", + "baseCurrency": "BTC", + "baseCurrencyPrice": "1", + "baseAmount": "1.1" + }], + "marginAccounts": [{ + "currency": "BTC", + "balance": "1.1", + "available": "1.1", + "holds": "0", + "baseCurrency": "BTC", + "baseCurrencyPrice": "1", + "baseAmount": "1.1" + }] + } + ] + """ + return await self._request('GET', '/api/v1/sub-accounts') + + async def get_transferable(self, currency, account_type, **kwargs): + """ + https://docs.kucoin.com/#get-the-transferable + :param currency: currency (Mandatory) + :type: str + :param account_type: The account type (Mandatory) + :type: str + :return: + { + "currency": "KCS", + "balance": "0", + "available": "0", + "holds": "0", + "transferable": "0" + } + """ + params = { + 'currency': currency, + 'type': account_type + } + if kwargs: + params.update(kwargs) + return await self._request('GET', '/api/v1/accounts/transferable', params=params) + + async def transfer_master_sub(self, currency, amount, direction, subUserId, clientOid='', accountType=None, + subAccountType=None): + """ + https://docs.kucoin.com/#transfer-between-master-user-and-sub-user + :param currency: currency (Mandatory) + :type: str + :param amount: Transfer amount, the amount is a positive integer multiple of the currency precision. (Mandatory) + :type: str + :param direction: OUT — the master user to sub user,IN — the sub user to the master user. (Mandatory) + :type: str + :param accountType: The account type of the master user (Optional) + :type: str + :param subAccountType: The account type of the sub user (Optional) + :type: str + :param subUserId: the user ID of a sub-account. (Mandatory) + :type: str + :param clientOid: Unique order id created by users to identify their orders, e.g. UUID. (Mandatory) + :type: str + :return: + { + "orderId": "5cbd870fd9575a18e4438b9a" + } + """ + params = { + 'currency': currency, + 'amount': amount, + 'direction': direction, + 'subUserId': subUserId + } + if accountType: + params['accountType'] = accountType + if subAccountType: + params['subAccountType'] = subAccountType + if not clientOid: + clientOid = self.return_unique_id + params['clientOid'] = clientOid + return await self._request('POST', '/api/v2/accounts/sub-transfer', params=params) + + async def inner_transfer(self, currency, from_payer, to_payee, amount, clientOid=''): + """ + https://docs.kucoin.com/#inner-transfer + :param currency: currency (Mandatory) + :type: str + :param from_payer: Account type of payer (Mandatory) + :type: str + :param to_payee: Account type of payee (Mandatory) + :type: str + :param amount: Transfer amount, the amount is a positive integer multiple of the currency precision. (Mandatory) + :type: str + :param clientOid: Unique order id created by users to identify their orders, e.g. UUID. (Mandatory) + :type: str + :return: + { + "orderId": "5bd6e9286d99522a52e458de" + } + """ + params = { + 'currency': currency, + 'from': from_payer, + 'to': to_payee, + 'amount': amount + } + if not clientOid: + clientOid = self.return_unique_id + params['clientOid'] = clientOid + return await self._request('POST', '/api/v2/accounts/inner-transfer', params=params) + + async def create_deposit_address(self, currency, chain=None): + """ + https://docs.kucoin.com/#create-deposit-address + :param currency: currency (Mandatory) + :type: str + :param chain: The chain name of currency, e.g. The available value for USDT are OMNI, ERC20, TRC20,default is + OMNI. This only apply for multi-chain currency, and there is no need for single chain currency. (Optional) + :type: str + :return: + { + "address": "0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1", + "memo": "5c247c8a03aa677cea2a251d", //tag + "chain": "OMNI" + } + """ + params = { + 'currency': currency + } + if chain: + params['chain'] = chain + return await self._request('POST', '/api/v1/deposit-addresses', params=params) + + async def flex_transfer(self, clientOid,amount,fromAccountType,type,toAccountType, + currency=None,fromUserId=None,fromAccountTag=None,toUserId=None,toAccountTag=None): + """ + FlexTransfer + https://www.kucoin.com/docs/rest/funding/transfer/flextransfer + """ + params = { + "clientOid": clientOid, + "type": type, + "amount": amount, + "fromAccountType": fromAccountType, + "toAccountType": toAccountType + } + + if currency: + params['currency'] = currency + if fromUserId: + params['fromUserId'] = fromUserId + if fromAccountTag: + params['fromAccountTag'] = fromAccountTag + if toUserId: + params['toUserId'] = toUserId + if toAccountTag: + params['toAccountTag'] = toAccountTag + return await self._request('POST', '/api/v3/accounts/universal-transfer', params=params) + + async def get_deposit_addressv2(self, currency, chain=None): + """ + https://docs.kucoin.com/#get-deposit-addresses-v2 + :param currency: currency (Mandatory) + :type: str + :param chain: The chain name of currency, e.g. The available value for USDT are OMNI, ERC20, TRC20,default is + OMNI. This only apply for multi-chain currency, and there is no need for single chain currency. (Optional) + :type: str + :return: + [{ + "address": "0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1", + "memo": "5c247c8a03aa677cea2a251d", //tag + "chain": "OMNI", + "contractAddress": "" + }] + """ + params = { + 'currency': currency + } + if chain: + params['chain'] = chain + return await self._request('GET', '/api/v2/deposit-addresses', params=params) + + async def get_deposit_address(self, currency, chain=None): + """ + https://docs.kucoin.com/#get-deposit-address + :param currency: currency (Mandatory) + :type: str + :param chain: The chain name of currency, e.g. The available value for USDT are OMNI, ERC20, TRC20,default is + OMNI. This only apply for multi-chain currency, and there is no need for single chain currency. (Optional) + :type: str + :return: + { + "address": "0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1", + "memo": "5c247c8a03aa677cea2a251d", //tag + "chain": "OMNI" + } + """ + params = { + 'currency': currency + } + if chain: + params['chain'] = chain + return await self._request('GET', '/api/v1/deposit-addresses', params=params) + + async def get_deposit_list(self, **kwargs): + """ + https://docs.kucoin.com/#get-deposit-list + :param kwargs: [optional] currency, startAt, endAt, status, currentPage, pageSize + :return: + { + "currentPage": 1, + "pageSize": 5, + "totalNum": 2, + "totalPage": 1, + "items": [{ + "address": "0x5f047b29041bcfdbf0e4478cdfa753a336ba6989", + "memo": "5c247c8a03aa677cea2a251d", + "amount": 1, + "fee": 0.0001, + "currency": "KCS", + "isInner": false, + "walletTxId": "5bbb57386d99522d9f954c5a@test004", + "status": "SUCCESS", + "remark": "test", + "createdAt": 1544178843000, + "updatedAt": 1544178891000 + }, { + "address": "0x5f047b29041bcfdbf0e4478cdfa753a336ba6989", + "memo": "5c247c8a03aa677cea2a251d", + "amount": 1, + "fee": 0.0001, + "currency": "KCS", + "isInner": false, + "walletTxId": "5bbb57386d99522d9f954c5a@test003", + "status": "SUCCESS", + "remark": "test", + "createdAt": 1544177654000, + "updatedAt": 1544178733000 + }] + } + """ + params = {} + if kwargs: + params.update(kwargs) + return await self._request('GET', '/api/v1/deposits', params=params) + + async def get_deposit_list_v1(self, **kwargs): + """ + https://docs.kucoin.com/#get-v1-historical-deposits-list + :param kwargs: [optional] currency, startAt, endAt, status, currentPage, pageSize + :return: + { + "currentPage": 1, + "pageSize": 5, + "totalNum": 2, + "totalPage": 1, + "items": [{ + "address": "0x5f047b29041bcfdbf0e4478cdfa753a336ba6989", + "memo": "5c247c8a03aa677cea2a251d", + "amount": 1, + "fee": 0.0001, + "currency": "KCS", + "isInner": false, + "walletTxId": "5bbb57386d99522d9f954c5a@test004", + "status": "SUCCESS", + "remark": "test", + "createdAt": 1544178843000, + "updatedAt": 1544178891000 + }, { + "address": "0x5f047b29041bcfdbf0e4478cdfa753a336ba6989", + "memo": "5c247c8a03aa677cea2a251d", + "amount": 1, + "fee": 0.0001, + "currency": "KCS", + "isInner": false, + "walletTxId": "5bbb57386d99522d9f954c5a@test003", + "status": "SUCCESS", + "remark": "test", + "createdAt": 1544177654000, + "updatedAt": 1544178733000 + }] + } + """ + params = {} + if kwargs: + params.update(kwargs) + return await self._request('GET', '/api/v1/hist-deposits', params=params) + + async def get_withdrawal_list(self, **kwargs): + """ + https://docs.kucoin.com/#get-withdrawals-list + :param kwargs: [optional] currency, status, startAt, endAt, currentPage , pageSize + :return: + { + "currentPage": 1, + "pageSize": 10, + "totalNum": 1, + "totalPage": 1, + "items": [{ + "id": "5c2dc64e03aa675aa263f1ac", + "address": "0x5bedb060b8eb8d823e2414d82acce78d38be7fe9", + "memo": "", + "currency": "ETH", + "amount": 1.0000000, + "fee": 0.0100000, + "walletTxId": "3e2414d82acce78d38be7fe9", + "isInner": false, + "status": "FAILURE", + "remark": "test", + "createdAt": 1546503758000, + "updatedAt": 1546504603000 + }] + } + """ + params = {} + if kwargs: + params.update(kwargs) + + return await self._request('GET', '/api/v1/withdrawals', params=params) + + async def get_hist_withdrawal_list(self, **kwargs): + """ + https://docs.kucoin.com/#get-v1-historical-withdrawals-list + :param kwargs: [optional] currency, status, startAt, endAt, currentPage , pageSize + :return: + { + "currentPage": 1, + "pageSize": 1, + "totalNum": 2, + "totalPage": 2, + "items": [{ + "currency": "BTC", + "createAt": 1526723468, + "amount": "0.534", + "address": "33xW37ZSW4tQvg443Pc7NLCAs167Yc2XUV", + "walletTxId": "aeacea864c020acf58e51606169240e96774838dcd4f7ce48acf38e3651323f4", + "isInner": false, + "status": "SUCCESS" + }] + } + """ + params = {} + if kwargs: + params.update(kwargs) + + return await self._request('GET', '/api/v1/hist-withdrawals', params=params) + + async def get_withdrawal_quota(self, currency, chain=None): + """ + https://docs.kucoin.com/#get-withdrawal-quotas + :param currency: currency (Mandatory) + :type: str + :param chain: The chain name of currency, e.g. The available value for USDT are OMNI, ERC20, TRC20, default is + OMNI. This only apply for multi-chain currency, and there is no need for single chain currency. (Optional) + :type: str + :return: + { + "currency": "KCS", + "limitBTCAmount": "2.0", + "usedBTCAmount": "0", + "limitAmount": "75.67567568", + "remainAmount": "75.67567568", + "availableAmount": "9697.41991348", + "withdrawMinFee": "0.93000000", + "innerWithdrawMinFee": "0.00000000", + "withdrawMinSize": "1.4", + "isWithdrawEnabled": true, + "precision": 8, //withdrawal precision + "chain": "OMNI" + } + """ + params = { + 'currency': currency + } + if chain: + params['chain'] = chain + return await self._request('GET', '/api/v1/withdrawals/quotas', params=params) + + async def apply_withdrawal(self, currency, address, amount, **kwargs): + """ + https://docs.kucoin.com/#apply-withdraw-2 + :param currency: Currency. (Mandatory) + :type: str + :param address: Withdrawal address (Mandatory) + :type: str + :param amount: Withdrawal amount, a positive number which is a multiple of the amount precision + (fees excluded) (Mandatory) + :type: float + :param kwargs: [Optional] memo, isInner, remark, chain + :return: + { + "withdrawalId": "5bffb63303aa675e8bbe18f9" + } + """ + params = { + 'currency': currency, + 'address': address, + 'amount': amount + } + if kwargs: + params.update(kwargs) + + return await self._request('POST', '/api/v1/withdrawals', params=params) + + async def cancel_withdrawal(self, withdrawalId): + """ + https://docs.kucoin.com/#cancel-withdrawal + :param withdrawalId: Path parameter, a unique ID for a withdrawal order (Mandatory) + :type: str + :return: + """ + return await self._request('DELETE', '/api/v1/withdrawals/{withdrawalId}'.format(withdrawalId=withdrawalId)) + + async def get_sub_user_page(self, **kwargs): + """ + https://docs.kucoin.com/#get-paginated-list-of-sub-accounts + :param kwargs: [optional] currentPage , pageSize + :return: + { + "currentPage":1, + "pageSize":100, + "totalNum":1, + "totalPage":1, + "items":[ + { + "userId":"635002438793b80001dcc8b3", + "uid":62356, + "subName":"margin01", + "status":2, + "type":4, + "access":"Margin", + "createdAt":1666187844000, + "remarks":null + } + ] + } + """ + params = {} + if kwargs: + params.update(kwargs) + return await self._request('GET', '/api/v2/sub/user', params=params) + + async def get_account_summary_info(self): + """ + https://docs.kucoin.com/#get-account-summary-info-v2 + :return: + { + "level" : 0, + "subQuantity" : 5, + "maxDefaultSubQuantity" : 5, + "maxSubQuantity" : 5, + + "spotSubQuantity" : 5, + "marginSubQuantity" : 5, + "futuresSubQuantity" : 5, + + "maxSpotSubQuantity" : 0, + "maxMarginSubQuantity" : 0, + "maxFuturesSubQuantity" : 0 + } + """ + return await self._request('GET', '/api/v2/user-info') + + async def create_sub_account(self, password, sub_name, access, **kwargs): + """ + https://docs.kucoin.com/#create-sub-account-v2 + :param password: Password(7-24 characters, must contain letters and numbers, cannot only contain numbers or include special characters) + :type: str + :param sub_name: Sub-account name(must contain 7-32 characters, at least one number and one letter. Cannot contain any spaces.) + :type: str + :param access: Permission (types include Spot, Futures, Margin permissions, which can be used alone or in combination). + :type: str + :param kwargs: [Optional] remarks + :return: + { + "uid": 9969082973, + "subName": "AAAAAAAAAA0007", + "remarks": "remark", + "access": "Spot" + } + """ + params = { + 'password': password, + 'subName': sub_name, + 'access': access + } + if kwargs: + params.update(kwargs) + + return await self._request('POST', '/api/v2/sub/user/created', params=params) + + async def get_sub_account_api_list(self, sub_name, **kwargs): + """ + https://docs.kucoin.com/#get-sub-account-spot-api-list + :param sub_name: Sub-account name. + :type: str + :param kwargs: [optional] apiKey + :return: + { + "subName": "AAAAAAAAAAAAA0022", + "remark": "hytest01-01", + "apiKey": "63032453e75087000182982b", + "permission": "General", + "ipWhitelist": "", + "createdAt": 1661150291000 + } + """ + params = { + 'subName': sub_name + } + if kwargs: + params.update(kwargs) + return await self._request('GET', '/api/v1/sub/api-key', params=params) + + async def create_apis_for_sub_account(self, sub_name, passphrase, remark, **kwargs): + """ + https://docs.kucoin.com/#create-spot-apis-for-sub-account + :param sub_name: Sub-account name(must contain 7-32 characters, at least one number and one letter. Cannot contain any spaces.) + :type: str + :param passphrase: Password(Must contain 7-32 characters. Cannot contain any spaces.) + :type: str + :param remark: Remarks(1~24 characters) + :type: str + :param kwargs: [Optional] permission, ipWhitelist, expire + :return: + { + "subName": "AAAAAAAAAA0007", + "remark": "remark", + "apiKey": "630325e0e750870001829864", + "apiSecret": "110f31fc-61c5-4baf-a29f-3f19a62bbf5d", + "passphrase": "passphrase", + "permission": "General", + "ipWhitelist": "", + "createdAt": 1661150688000 + } + """ + params = { + 'subName': sub_name, + 'passphrase': passphrase, + 'remark': remark + } + if kwargs: + params.update(kwargs) + + return await self._request('POST', '/api/v1/sub/api-key', params=params) + + async def modify_sub_account_apis(self, sub_name, api_key, passphrase, **kwargs): + """ + https://docs.kucoin.com/#modify-sub-account-spot-apis + :param sub_name: Sub-account name + :type: str + :param passphrase: Password of API key + :type: str + :param api_key: API-Key(Sub-account APIKey) + :type: str + :param kwargs: [Optional] permission, ipWhitelist, expire + :return: + { + "subName": "AAAAAAAAAA0007", + "apiKey": "630329b4e7508700018298c5", + "permission": "General", + "ipWhitelist": "127.0.0.1", + } + """ + params = { + 'subName': sub_name, + 'passphrase': passphrase, + 'apiKey': api_key + } + if kwargs: + params.update(kwargs) + + return await self._request('POST', '/api/v1/sub/api-key/update', params=params) + + async def delete_sub_account_apis(self, sub_name, api_key, passphrase): + """ + https://docs.kucoin.com/#delete-sub-account-spot-apis + :param sub_name: Sub-account name(The sub-account name corresponding to the API key) + :type: str + :param passphrase: Password(Password of the API key) + :type: str + :param api_key: API-Key(API key to be deleted) + :type: str + :return: + { + "subName": "AAAAAAAAAA0007", + "apiKey": "630325e0e750870001829864" + } + """ + params = { + 'subName': sub_name, + 'passphrase': passphrase, + 'apiKey': api_key + } + + return await self._request('DELETE', '/api/v1/sub/api-key', params=params) + + async def get_sub_account_page_info(self, **kwargs): + """ + https://docs.kucoin.com/#get-paginated-sub-account-information + :param kwargs: [optional] currentPage , pageSize + :return: + { + "currentPage": 1, + "pageSize": 10, + "totalNum": 14, + "totalPage": 2, + "items": [ + { + "subUserId": "635002438793b80001dcc8b3", + "subName": "margin03", + "mainAccounts": [ + { + "currency": "00", + "balance": "0", + "available": "0", + "holds": "0", + "baseCurrency": "BTC", + "baseCurrencyPrice": "125.63", + "baseAmount": "0" + } + ] + } + ] + } + """ + params = {} + if kwargs: + params.update(kwargs) + return await self._request('GET', '/api/v2/sub-accounts', params=params) + + async def get_hf_account_ledgers(self, **kwargs): + """ + https://docs.kucoin.com/spot-hf/#account-ledger-in-high-frequency-trading-accounts + :param kwargs: [optional] currency, direction, bizType, lastId, limit, startAt, endAt + :return: + [ + { + "id": "42852417537", + "currency": "CSP", + "amount": "1.00000000", + "fee": "0.00000000", + "balance": "99999986.99999999", + "accountType": "TRADE_HF", + "bizType": "TRADE_EXCHANGE", + "direction": "in", + "createdAt": "1661347205743", + "context": "{'symbol':'CSP-USDT','orderId':'6306257dd9180300014c8d47','tradeId':'609522034689'}" + }, + { + "id": "42852401152", + "currency": "CSP", + "amount": "1.00000000", + "fee": "0.00000000", + "balance": "99999985.99999999", + "accountType": "TRADE_HF", + "bizType": "TRADE_EXCHANGE", + "direction": "out", + "createdAt": "1661347205743", + "context": "{'symbol':'CSP-USDT','orderId':'63062585d9180300014c8d50','tradeId':'609522034689'}" + } + ] + """ + params = {} + if kwargs: + params.update(kwargs) + return await self._request('GET', '/api/v1/hf/accounts/ledgers', params=params) + + async def transfer_to_hf_account(self, client_oid, currency, from_payer, amount): + """ + transfer to the high-frequency account,return high-frequency account info. + :param client_oid: Client Order Id,a unique identifier created by the user, using UUID is recommended + :type: str + :param currency: currency + :type: str + :param from_payer: Payment account type: main(main account), trade(trading account), trade_hf(high-frequency trading account) + :type: str + :param amount: Transfer amount, the precision is the precision of the currency multiplied by a positive integer + :type: float + :return: + [ + { + "balance": "3027.25165335", + "available": "3027.25165335", + "holds": "0", + "currency": "USDT", + "id": "2560047104", + "type": "trade_hf" + } + ] + """ + params1 = { + 'clientOid': client_oid, + 'currency': currency, + 'from': from_payer, + 'amount': amount, + 'to': 'trade_hf' + } + self._request('POST', '/api/v2/accounts/inner-transfer', params=params1) + params2 = { + 'currency': currency, + 'type': 'trade_hf' + } + return await self._request('GET', '/api/v1/accounts', params=params2) diff --git a/requirements.txt b/requirements.txt index 1ed21c7..6d20a3f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,3 @@ requests -websockets \ No newline at end of file +websockets +aiohttp \ No newline at end of file diff --git a/setup.py b/setup.py index 9a3220b..99487b9 100644 --- a/setup.py +++ b/setup.py @@ -8,13 +8,14 @@ name='kucoin-python', version='v1.0.24', packages=['kucoin', 'kucoin/base_request', 'kucoin/margin', 'kucoin/market', 'kucoin/trade', 'kucoin/user','kucoin/lending','kucoin/earn', - 'kucoin/websocket', 'kucoin/ws_token'], + 'kucoin/websocket', 'kucoin/ws_token', 'kucoin/asyncio/async_request', 'kucoin/asyncio/earn', 'kucoin/asyncio/lending', 'kucoin/asyncio/margin', + 'kucoin/asyncio/market', 'kucoin/asyncio/trade', 'kucoin/asyncio/user', 'kucoin/asyncio'], license="MIT", author='Arthur', author_email="arthur.zhang@kucoin.com", url='https://github.com/Kucoin/kucoin-python-sdk', description="kucoin-api-sdk", - install_requires=['requests', 'websockets'], + install_requires=['requests', 'websockets', 'aiohttp'], classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License",