From 7ccf770131f89fdadf193a5ea9c651888f3b3695 Mon Sep 17 00:00:00 2001 From: yzh-pelle <81404729+yzh-pelle@users.noreply.github.com> Date: Sat, 2 Nov 2024 12:25:04 +0300 Subject: [PATCH 01/60] hf orders added --- kucoin/client.py | 349 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 348 insertions(+), 1 deletion(-) diff --git a/kucoin/client.py b/kucoin/client.py index 5740fcd..8468ee9 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -953,6 +953,81 @@ def create_market_order( return self._post('orders', True, data=data) + def hf_create_market_order( + self, symbol, side, size=None, funds=None, client_oid=None, stp=None, tags=None, remark=None + ): + """Create a hf market order + + One of size or funds must be set + + https://docs.kucoin.com/#place-hf-order + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param side: buy or sell + :type side: string + :param size: (optional) Desired amount in base currency + :type size: string + :param funds: (optional) Desired amount of quote currency to use + :type funds: string + :param client_oid: (optional) Unique order id (default flat_uuid()) + :type client_oid: string + :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) + :type stp: string + :param tags: (optional) order tag, length cannot exceed 20 characters (ASCII) + :type tags: string + :param remark: (optional) remark for the order, max 100 utf8 characters + :type remark: string + + .. code:: python + + order = client.hf_create_market_order('NEO', Client.SIDE_BUY, size=20) + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "orderId": "5bd6e9286d99522a52e458de", + "clientOid": "11223344" + } + } + + :raises: KucoinResponseException, KucoinAPIException, MarketOrderException + + """ + + if not size and not funds: + raise MarketOrderException('Need size or fund parameter') + + if size and funds: + raise MarketOrderException('Need size or fund parameter not both') + + data = { + 'symbol': symbol, + 'side': side, + 'type': self.ORDER_MARKET + } + + if size: + data['size'] = size + if funds: + data['funds'] = funds + if client_oid: + data['clientOid'] = client_oid + else: + data['clientOid'] = flat_uuid() + if stp: + data['stp'] = stp + if tags: + data['tags'] = tags + if remark: + data['remark'] = remark + + return self._post('hf/orders', True, data=data) + def create_limit_order(self, symbol, side, price, size, client_oid=None, remark=None, time_in_force=None, stop=None, stop_price=None, stp=None, trade_type=None, cancel_after=None, post_only=None, @@ -1062,6 +1137,105 @@ def create_limit_order(self, symbol, side, price, size, client_oid=None, remark= return self._post('orders', True, data=data) + def hf_create_limit_order(self, symbol, side, price, size, client_oid=None, stp=None, + tags=None, remark=None, time_in_force=None, cancel_after=None, post_only=None, + hidden=None, iceberg=None, visible_size=None): + """Create a hf order + + https://docs.kucoin.com/#place-hf-order + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param side: buy or sell + :type side: string + :param price: Name of coin + :type price: string + :param size: Amount of base currency to buy or sell + :type size: string + :param client_oid: (optional) Unique order_id default flat_uuid() + :type client_oid: string + :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) + :type stp: string + :param tags: (optional) order tag, length cannot exceed 20 characters (ASCII) + :type tags: string + :param remark: (optional) remark for the order, max 100 utf8 characters + :type remark: string + :param time_in_force: (optional) GTC, GTT, IOC, or FOK (default is GTC) + :type time_in_force: string + :param cancel_after: (optional) number of seconds to cancel the order if not filled + required time_in_force to be GTT + :type cancel_after: string + :param post_only: (optional) indicates that the order should only make liquidity. If any part of + the order results in taking liquidity, the order will be rejected and no part of it will execute. + :type post_only: bool + :param hidden: (optional) Orders not displayed in order book + :type hidden: bool + :param iceberg: (optional) Only visible portion of the order is displayed in the order book + :type iceberg: bool + :param visible_size: (optional) The maximum visible size of an iceberg order + :type visible_size: bool + + .. code:: python + + order = client.hf_create_limit_order('KCS-BTC', Client.SIDE_BUY, '0.01', '1000') + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "orderId": "5bd6e9286d99522a52e458de", + "clientOid": "11223344" + } + } + + :raises: KucoinResponseException, KucoinAPIException, LimitOrderException + + """ + + if cancel_after and time_in_force != self.TIMEINFORCE_GOOD_TILL_TIME: + raise LimitOrderException('Cancel after only works with time_in_force = "GTT"') + + if hidden and iceberg: + raise LimitOrderException('Order can be either "hidden" or "iceberg"') + + if iceberg and not visible_size: + raise LimitOrderException('Iceberg order requires visible_size') + + data = { + 'symbol': symbol, + 'side': side, + 'type': self.ORDER_LIMIT, + 'price': price, + 'size': size + } + + if client_oid: + data['clientOid'] = client_oid + else: + data['clientOid'] = flat_uuid() + if stp: + data['stp'] = stp + if tags: + data['tags'] = tags + if remark: + data['remark'] = remark + if time_in_force: + data['timeInForce'] = time_in_force + if cancel_after: + data['cancelAfter'] = cancel_after + if post_only: + data['postOnly'] = post_only + if hidden: + data['hidden'] = hidden + if iceberg: + data['iceberg'] = iceberg + data['visible_size'] = visible_size + + return self._post('hf/orders', True, data=data) + def cancel_order(self, order_id): """Cancel an order @@ -1119,7 +1293,81 @@ def cancel_order_by_client_oid(self, client_oid): """ - return self._delete('order/client-order/{}'.format(client_oid), True) + return self._delete('hf/orders/{}'.format(client_oid), True) + + def hf_cancel_order(self, order_id, symbol): + """Cancel a hf order by the orderId + + https://docs.kucoin.com/#cancel-hf-order-by-orderid + + :param order_id: OrderId + :type order_id: string + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + + .. code:: python + + res = client.hf_cancel_order_by_order_id('5bd6e9286d99522a52e458de', 'KCS-BTC') + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "orderId": "630625dbd9180300014c8d52" + } + } + + :raises: KucoinResponseException, KucoinAPIException + + KucoinAPIException If order_id is not found + + """ + + data = { + 'symbol': symbol + } + + return self._delete('hf/orders/{}'.format(order_id), True, data=data) + + def hf_cancel_order_by_client_oid(self, client_oid, symbol): + """Cancel a hf order by the clientOid + + https://docs.kucoin.com/#cancel-hf-order-by-clientoid + + :param client_oid: ClientOid + :type client_oid: string + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + + .. code:: python + + res = client.hf_cancel_order_by_client_oid('6d539dc614db3', 'KCS-BTC') + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "clientOid": "6d539dc614db3" + } + } + + :raises: KucoinResponseException, KucoinAPIException + + KucoinAPIException If order_id is not found + + """ + + data = { + 'symbol': symbol + } + + return self._delete('hf/orders/client-order{}'.format(client_oid), True, data=data) def cancel_all_orders(self, symbol=None): """Cancel all orders @@ -1148,6 +1396,38 @@ def cancel_all_orders(self, symbol=None): data['symbol'] = symbol return self._delete('orders', True, data=data) + def hf_cancel_all_orders(self): + """Cancel all orders + + https://docs.kucoin.com/#cancel-all-hf-orders + + .. code:: python + + res = client.hf_cancel_all_orders() + + :returns: ApiResponse + + .. code:: python + + { + "succeedSymbols": [ + "BTC-USDT", + "ETH-USDT" + ], + "failedSymbols": [ + { + "symbol": "BTC-USDT", + "error": "can't cancel, system timeout" + } + ], + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + return self._delete('hf/orders/cancelAll', True) + + def get_orders(self, symbol=None, status=None, side=None, order_type=None, start=None, end=None, page=None, limit=None, trade_type='TRADE'): """Get list of orders @@ -1368,6 +1648,73 @@ def get_order(self, order_id): return self._get('orders/{}'.format(order_id), True) + def hf_get_order(self, order_id, symbol): + """Get hf order details by orderId + + https://docs.kucoin.com/#get-hf-order-details-by-orderid + + :param order_id: orderId value + :type order_id: str + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + + .. code:: python + + order = client.hf_get_order('5c35c02703aa673ceec2a168', 'KCS-BTC') + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "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" + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('hf/orders/{}'.format(order_id), True, data=data) + def get_order_by_client_oid(self, client_oid): """Get order details by clientOid From ef96e39823ac8b12feba10fc1692c3dccbea5b4d Mon Sep 17 00:00:00 2001 From: yzh-pelle <81404729+yzh-pelle@users.noreply.github.com> Date: Sat, 2 Nov 2024 13:17:29 +0300 Subject: [PATCH 02/60] get_user_info added --- kucoin/client.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/kucoin/client.py b/kucoin/client.py index 8468ee9..ecccd47 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -2340,3 +2340,35 @@ def get_ws_endpoint(self, private=False): path = 'bullet-private' return self._post(path, signed) + + def get_user_info (self): + """Get account summary info + + https://www.kucoin.com/docs/rest/account/basic-info/get-account-summary-info + + .. code:: python + + user_info = client.get_user_info() + + :returns: ApiResponse + + .. code:: python + + { + "level": 0, + "subQuantity": 5, + "maxDefaultSubQuantity": 5, + "maxSubQuantity": 5, + "spotSubQuantity": 5, + "marginSubQuantity": 5, + "futuresSubQuantity": 5, + "maxSpotSubQuantity": 0, + "maxMarginSubQuantity": 0, + "maxFuturesSubQuantity": 0 + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + return self._get('user-info', True, api_version=self.API_VERSION2) From c47a68aae6b79e319866ffb7ca81e38c847c2770 Mon Sep 17 00:00:00 2001 From: yzh-pelle <81404729+yzh-pelle@users.noreply.github.com> Date: Sat, 2 Nov 2024 13:41:09 +0300 Subject: [PATCH 03/60] get_account_activity updated with **params --- kucoin/client.py | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index ecccd47..ffdeb2e 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -421,7 +421,7 @@ def create_account(self, account_type, currency): return self._post('accounts', True, data=data) - def get_account_activity(self, currency=None, direction=None, biz_type=None, start=None, end=None, page=None, limit=None): + def get_account_activity(self, currency=None, direction=None, biz_type=None, start=None, end=None, page=None, limit=None, **params): """Get list of account activity https://docs.kucoin.com/#get-account-history @@ -493,25 +493,22 @@ def get_account_activity(self, currency=None, direction=None, biz_type=None, sta """ - data = {} if currency: - data['currency'] = currency + params['currency'] = currency if direction: - data['direction'] = direction + params['direction'] = direction if biz_type: - data['bizType'] = biz_type + params['bizType'] = biz_type if start: - data['startAt'] = start - if start: - data['startAt'] = start + params['startAt'] = start if end: - data['endAt'] = end + params['endAt'] = end if page: - data['currentPage'] = page + params['currentPage'] = page if limit: - data['pageSize'] = limit + params['pageSize'] = limit - return self._get('accounts/ledgers', True, data=data) + return self._get('accounts/ledgers', True, data=params) def create_inner_transfer(self, currency, from_type, to_type, amount, order_id=None): """Transfer fund among accounts on the platform @@ -2372,3 +2369,5 @@ def get_user_info (self): """ return self._get('user-info', True, api_version=self.API_VERSION2) + + From 1f32786a3c881f1202b4947ae7ad5e22bd5bf675 Mon Sep 17 00:00:00 2001 From: yzh-pelle <81404729+yzh-pelle@users.noreply.github.com> Date: Sat, 2 Nov 2024 14:04:41 +0300 Subject: [PATCH 04/60] hf_get_account_activity added --- kucoin/client.py | 61 ++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 54 insertions(+), 7 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index ffdeb2e..5ac5f9e 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -311,7 +311,7 @@ def get_currency(self, currency): def get_accounts(self, currency=None, account_type=None): """Get a list of accounts - https://docs.kucoin.com/#accounts + https://www.kucoin.com/docs/rest/account/basic-info/get-account-list-spot-margin-trade_hf :param currency: optional Currency code :type currency: string @@ -362,7 +362,7 @@ def get_accounts(self, currency=None, account_type=None): def get_account(self, account_id): """Get an individual account - https://docs.kucoin.com/#get-an-account + https://www.kucoin.com/docs/rest/account/basic-info/get-account-detail-spot-margin-trade_hf :param account_id: ID for account - from list_accounts() :type account_id: string @@ -424,7 +424,7 @@ def create_account(self, account_type, currency): def get_account_activity(self, currency=None, direction=None, biz_type=None, start=None, end=None, page=None, limit=None, **params): """Get list of account activity - https://docs.kucoin.com/#get-account-history + https://www.kucoin.com/docs/rest/account/basic-info/get-account-ledgers-spot-margin :param currency: (optional) currency name :type currency: string @@ -493,10 +493,6 @@ def get_account_activity(self, currency=None, direction=None, biz_type=None, sta """ - if currency: - params['currency'] = currency - if direction: - params['direction'] = direction if biz_type: params['bizType'] = biz_type if start: @@ -510,6 +506,57 @@ def get_account_activity(self, currency=None, direction=None, biz_type=None, sta return self._get('accounts/ledgers', True, data=params) + def hf_get_account_activity(self, currency=None, direction=None, biz_type=None, start=None, end=None, limit=None, last_id=None, **params): + """Get list of hf account activity + + https://www.kucoin.com/docs/rest/account/basic-info/get-account-ledgers-trade_hf + + :param currency: (optional) currency name + :type currency: string + :param direction: (optional) Side: in - Receive, out - Send + :type direction: string + :param biz_type: (optional) Business type: DEPOSIT, WITHDRAW, TRANSFER, SUB_TRANSFER,TRADE_EXCHANGE, MARGIN_EXCHANGE, KUCOIN_BONUS. + :type biz_type: string + :param start: (optional) Start time as unix timestamp + :type start: string + :param end: (optional) End time as unix timestamp + :type end: string + :param limit: (optional) Number of results to return - default 100 + :type limit: int + :param last_id: (optional) The id of the last set of data from the previous batch of data. By default, the latest information is given. + :type last_id: int + + .. code:: python + + history = client.hf_get_account_activity('5bd6e9216d99522a52e458d6') + + history = client.hf_get_account_activity('5bd6e9216d99522a52e458d6', start='1540296039000') + + history = client.hf_get_account_activity('5bd6e9216d99522a52e458d6', limit=10) + + :returns: API Response + + .. code-block:: python + + + :raises: KucoinResponseException, KucoinAPIException + + """ + + if biz_type: + params['bizType'] = biz_type + if start: + params['startAt'] = start + if end: + params['endAt'] = end + if limit: + params['limit'] = limit + if last_id: + params['lastId'] = last_id + #todo test it + + return self._get('accounts/ledgers', True, data=params) + def create_inner_transfer(self, currency, from_type, to_type, amount, order_id=None): """Transfer fund among accounts on the platform From 8a98be223989ea9869d4adedc46d9ccbc3495108 Mon Sep 17 00:00:00 2001 From: yzh-pelle <81404729+yzh-pelle@users.noreply.github.com> Date: Sat, 2 Nov 2024 14:18:12 +0300 Subject: [PATCH 05/60] Update client.py --- kucoin/client.py | 40 +++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 5ac5f9e..59d3a74 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -492,19 +492,23 @@ def get_account_activity(self, currency=None, direction=None, biz_type=None, sta :raises: KucoinResponseException, KucoinAPIException """ - + data = {} + if currency: + data['currency'] = currency + if direction: + data['direction'] = direction if biz_type: - params['bizType'] = biz_type + data['bizType'] = biz_type if start: - params['startAt'] = start + data['startAt'] = start if end: - params['endAt'] = end + data['endAt'] = end if page: - params['currentPage'] = page + data['currentPage'] = page if limit: - params['pageSize'] = limit + data['pageSize'] = limit - return self._get('accounts/ledgers', True, data=params) + return self._get('accounts/ledgers', True, dict(data, **params)) def hf_get_account_activity(self, currency=None, direction=None, biz_type=None, start=None, end=None, limit=None, last_id=None, **params): """Get list of hf account activity @@ -536,26 +540,28 @@ def hf_get_account_activity(self, currency=None, direction=None, biz_type=None, :returns: API Response - .. code-block:: python - - :raises: KucoinResponseException, KucoinAPIException """ + #todo test and write the return value + data = {} + if currency: + data['currency'] = currency + if direction: + data['direction'] = direction if biz_type: - params['bizType'] = biz_type + data['bizType'] = biz_type if start: - params['startAt'] = start + data['startAt'] = start if end: - params['endAt'] = end + data['endAt'] = end if limit: - params['limit'] = limit + data['limit'] = limit if last_id: - params['lastId'] = last_id - #todo test it + data['lastId'] = last_id - return self._get('accounts/ledgers', True, data=params) + return self._get('accounts/ledgers', True, data=dict(data, **params)) def create_inner_transfer(self, currency, from_type, to_type, amount, order_id=None): """Transfer fund among accounts on the platform From 7aa10685850c865ac4b090623884d3418c3e2dfb Mon Sep 17 00:00:00 2001 From: yzh-pelle <81404729+yzh-pelle@users.noreply.github.com> Date: Sat, 2 Nov 2024 14:30:23 +0300 Subject: [PATCH 06/60] Update client.py --- kucoin/client.py | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 59d3a74..ce45fe5 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -178,6 +178,7 @@ def _handle_response(response): response. """ + print(response.text) if not str(response.status_code).startswith('2'): raise KucoinAPIException(response) try: @@ -540,11 +541,31 @@ def hf_get_account_activity(self, currency=None, direction=None, biz_type=None, :returns: API Response + .. code-block:: python + + { + "code": "200000", + "data": [ + { + "id": "981449530900577", + "currency": "ETH", + "amount": "0.00617410", + "fee": "0.00000000", + "tax": "0", + "balance": "0.00617410", + "accountType": "TRADE_HF", + "bizType": "TRADE_EXCHANGE", + "direction": "in", + "createdAt": "1730545211517", + "context": "{\"symbol\": \"ETH-USDT\",\"orderId\": \"6726063b4d742800076e0273\",\"tradeId\": \"10330457609226241\"}" + } + ] + } + :raises: KucoinResponseException, KucoinAPIException """ - #todo test and write the return value data = {} if currency: data['currency'] = currency @@ -561,7 +582,7 @@ def hf_get_account_activity(self, currency=None, direction=None, biz_type=None, if last_id: data['lastId'] = last_id - return self._get('accounts/ledgers', True, data=dict(data, **params)) + return self._get('hf/accounts/ledgers', True, data=dict(data, **params)) def create_inner_transfer(self, currency, from_type, to_type, amount, order_id=None): """Transfer fund among accounts on the platform From e1048e9295da354be924ccd2d2f179a26076afd6 Mon Sep 17 00:00:00 2001 From: yzh-pelle <81404729+yzh-pelle@users.noreply.github.com> Date: Sat, 2 Nov 2024 15:33:03 +0300 Subject: [PATCH 07/60] get_futures_account_activity added --- kucoin/client.py | 75 ++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 67 insertions(+), 8 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index ce45fe5..355020b 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -444,11 +444,11 @@ def get_account_activity(self, currency=None, direction=None, biz_type=None, sta .. code:: python - history = client.get_account_activity('5bd6e9216d99522a52e458d6') + history = client.get_account_activity() - history = client.get_account_activity('5bd6e9216d99522a52e458d6', start='1540296039000') + history = client.get_account_activity('ETH', start='1540296039000') - history = client.get_account_activity('5bd6e9216d99522a52e458d6', page=2, page_size=10) + history = client.get_account_activity('ETH', page=2, page_size=10) :returns: API Response @@ -493,6 +493,7 @@ def get_account_activity(self, currency=None, direction=None, biz_type=None, sta :raises: KucoinResponseException, KucoinAPIException """ + data = {} if currency: data['currency'] = currency @@ -511,10 +512,11 @@ def get_account_activity(self, currency=None, direction=None, biz_type=None, sta return self._get('accounts/ledgers', True, dict(data, **params)) - def hf_get_account_activity(self, currency=None, direction=None, biz_type=None, start=None, end=None, limit=None, last_id=None, **params): + def hf_get_account_activity(self, currency=None, direction=None, biz_type=None, start=None, end=None, limit=None, last_id=None, margin=False, **params): """Get list of hf account activity https://www.kucoin.com/docs/rest/account/basic-info/get-account-ledgers-trade_hf + https://www.kucoin.com/docs/rest/account/basic-info/get-account-ledgers-margin_hf :param currency: (optional) currency name :type currency: string @@ -530,14 +532,16 @@ def hf_get_account_activity(self, currency=None, direction=None, biz_type=None, :type limit: int :param last_id: (optional) The id of the last set of data from the previous batch of data. By default, the latest information is given. :type last_id: int + :param margin: (optional) If True, get margin account activity - default False + :type margin: bool .. code:: python - history = client.hf_get_account_activity('5bd6e9216d99522a52e458d6') + history = client.hf_get_account_activity() - history = client.hf_get_account_activity('5bd6e9216d99522a52e458d6', start='1540296039000') + history = client.hf_get_account_activity('ETH', start='1540296039000') - history = client.hf_get_account_activity('5bd6e9216d99522a52e458d6', limit=10) + history = client.hf_get_account_activity('ETH', margin=True, limit=10) :returns: API Response @@ -582,7 +586,62 @@ def hf_get_account_activity(self, currency=None, direction=None, biz_type=None, if last_id: data['lastId'] = last_id - return self._get('hf/accounts/ledgers', True, data=dict(data, **params)) + path = 'hf/accounts/ledgers' + if margin: + path = 'hf/margin/account/ledgers' + return self._get(path, True, data=dict(data, **params)) + + def get_futures_account_activity(self, currency=None, type=None, start=None, end=None, limit=None, offset=None, forward=True, **params): + """Get list of futures account activity + + https://www.kucoin.com/docs/rest/account/basic-info/get-account-ledgers-futures + + :param currency: (optional) currency name + :type currency: string + :param type: (optional) Type: RealisedPNL, Deposit, Withdrawal, Transferin, TransferOut. + :type type: string + :param start: (optional) Start time as unix timestamp + :type start: string + :param end: (optional) End time as unix timestamp + :type end: string + :param limit: (optional) Number of results to return - default 50 + :type limit: int + :param offset: (optional) Start offset. Generally, the only attribute of the last returned result of the previous request is used, and the first page is returned by default + :type offset: int + :param forward: (optional) This parameter functions to judge whether the lookup is forward or not. True means “yes” and False means “no” - default True + :type forward: bool + + .. code:: python + + history = client.get_futures_account_activity() + + history = client.get_account_activity('ETH', start='1540296039000') + + history = client.get_account_activity('ETH', forward=TRUE, page_size=10) + + :returns: API Response + + :raises: KucoinResponseException, KucoinAPIException + + """ + # todo check and add the response + data = {} + if currency: + data['currency'] = currency + if type: + data['type'] = type + if start: + data['startAt'] = start + if end: + data['endAt'] = end + if limit: + data['maxCount'] = limit + if offset: + data['offset'] = offset + if not forward: + data['forward'] = False + + return self._get('transaction-history', True, dict(data, **params)) def create_inner_transfer(self, currency, from_type, to_type, amount, order_id=None): """Transfer fund among accounts on the platform From 62a37246e8c2a62a1aea619c3e80a7d997a0b5c8 Mon Sep 17 00:00:00 2001 From: yzh-pelle <81404729+yzh-pelle@users.noreply.github.com> Date: Sat, 2 Nov 2024 17:27:25 +0300 Subject: [PATCH 08/60] create_subaccount added --- kucoin/client.py | 87 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 83 insertions(+), 4 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 355020b..ff691f3 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -309,7 +309,7 @@ def get_currency(self, currency): # User Account Endpoints - def get_accounts(self, currency=None, account_type=None): + def get_accounts(self, currency=None, account_type=None, **params): """Get a list of accounts https://www.kucoin.com/docs/rest/account/basic-info/get-account-list-spot-margin-trade_hf @@ -358,7 +358,45 @@ def get_accounts(self, currency=None, account_type=None): if account_type: data['type'] = account_type - return self._get('accounts', True, data=data) + return self._get('accounts', True, data=dict(data, **params)) + + def get_subaccounts(self, page=None, limit=None, **params): + """Get a list of subaccounts + + https://www.kucoin.com/docs/rest/account/sub-account/get-all-sub-accounts-info-v1- + + :param page: (optional) Current page - default 1 + :type page: int + :param limit: (optional) Number of results to return - default 10 + :type limit: int + + .. code:: python + + accounts = client.get_subaccounts() + accounts = client.get_subaccounts(page=2, limit=5) + + :returns: API Response + + .. code-block:: python + + + + :raises: KucoinResponseException, KucoinAPIException + + """ + # todo check and add the response + data = {} + if page: + data['currentPage'] = page + if limit: + data['pageSize'] = limit + + api_version = self.API_VERSION + if 'api_version' in params: + api_version = params['api_version'] + del params['api_version'] + + return self._get('sub/user', True, api_version, data=dict(data, **params)) def get_account(self, account_id): """Get an individual account @@ -419,9 +457,52 @@ def create_account(self, account_type, currency): 'type': account_type, 'currency': currency } + # todo check this endpoint return self._post('accounts', True, data=data) + def create_subaccount(self, password, sub_name, access, remarks=None, **params): + """Create a subaccount + + https://www.kucoin.com/docs/rest/account/sub-account/create-sub-account + + :param password: Password(7-24 characters, must contain letters and numbers, cannot only contain numbers or include special characters). + :type password: string + :param sub_name: Sub-account name(must contain 7-32 characters, at least one number and one letter. Cannot contain any spaces.) + :type sub_name: string + :param access: Permission (Spot, Futures, Margin permissions, which can be used alone or in combination). + :type access: string + :param remarks: optional Remarks(1~24 characters). + :type remarks: string + + .. code:: python + + account = client.create_subaccount('mypassword', 'mySubAccount', 'Spot') + account = client.create_subaccount('mypassword', 'mySubAccount', 'Spot, Margin', 'My Sub Account') + + :returns: API Response + + .. code-block:: python + + { + "id": "5bd6e9286d99522a52e458de" + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + # todo check and add the response (last time it was 100010: Network error. Please try again later) + data = { + 'password': password, + 'subName': sub_name, + 'access': access + } + if remarks: + data['remarks'] = remarks + + return self._post('sub/user/created', True, api_version=self.API_VERSION2, data=dict(data, **params)) + def get_account_activity(self, currency=None, direction=None, biz_type=None, start=None, end=None, page=None, limit=None, **params): """Get list of account activity @@ -2502,5 +2583,3 @@ def get_user_info (self): """ return self._get('user-info', True, api_version=self.API_VERSION2) - - From de8f9860c25bb048bde654541340937a6642dd8f Mon Sep 17 00:00:00 2001 From: rayBastard Date: Mon, 4 Nov 2024 17:25:32 +0200 Subject: [PATCH 09/60] get_subaccounts_v2 added --- kucoin/client.py | 71 ++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 63 insertions(+), 8 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index ff691f3..6eb719b 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -360,11 +360,50 @@ def get_accounts(self, currency=None, account_type=None, **params): return self._get('accounts', True, data=dict(data, **params)) - def get_subaccounts(self, page=None, limit=None, **params): + def get_subaccounts(self): """Get a list of subaccounts https://www.kucoin.com/docs/rest/account/sub-account/get-all-sub-accounts-info-v1- + .. code:: python + + accounts = client.get_subaccounts() + + :returns: API Response + + .. code-block:: python + + [ + { + "userId": "5cbd31ab9c93e9280cd36a0a", //subUserId + "uid": "1789234", + "subName": "kucoin1", + "type": 0, //type:0-nomal + "remarks": "kucoin1", + "access": "All" + }, + { + "userId": "5cbd31b89c93e9280cd36a0d", + "uid": "1789431", + "subName": "kucoin2", + "type": 1, //type:1-rebot + "remarks": "kucoin2", + "access": "All" + } + ] + + :raises: KucoinResponseException, KucoinAPIException + + """ + # todo check and add the response + + return self._get('sub/user', True) + + def get_subaccounts_v2(self, page=None, limit=None, **params): + """Get a list of subaccounts + + https://www.kucoin.com/docs/rest/account/sub-account/get-all-sub-accounts-info-v2- + :param page: (optional) Current page - default 1 :type page: int :param limit: (optional) Number of results to return - default 10 @@ -379,24 +418,40 @@ def get_subaccounts(self, page=None, limit=None, **params): .. code-block:: python - + { + "code": "200000", + "data": { + "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 + } + ] + } + } :raises: KucoinResponseException, KucoinAPIException """ # todo check and add the response + data = {} if page: data['currentPage'] = page if limit: data['pageSize'] = limit - api_version = self.API_VERSION - if 'api_version' in params: - api_version = params['api_version'] - del params['api_version'] - - return self._get('sub/user', True, api_version, data=dict(data, **params)) + return self._get('sub/user', True, api_version=self.API_VERSION2, data=dict(data, **params)) def get_account(self, account_id): """Get an individual account From 3bff03e1cdf13f22a7694c053530094b10f93e35 Mon Sep 17 00:00:00 2001 From: rayBastard Date: Mon, 4 Nov 2024 17:39:30 +0200 Subject: [PATCH 10/60] get_subaccount_balance added --- kucoin/client.py | 68 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/kucoin/client.py b/kucoin/client.py index 6eb719b..b244e3b 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -452,6 +452,74 @@ def get_subaccounts_v2(self, page=None, limit=None, **params): data['pageSize'] = limit return self._get('sub/user', True, api_version=self.API_VERSION2, data=dict(data, **params)) + + def get_subaccount_balance(self, sub_user_id, include_base_ammount, **params): + """Get the account info of a sub-user specified by the subUserId + + https://www.kucoin.com/docs/rest/account/sub-account/get-a-sub-account-balance + + :param sub_user_id: Sub account user id + :type sub_user_id: string + :param include_base_ammount: Include base amount or not + :type include_base_ammount: bool + + .. code:: python + + accounts = client.get_subaccount_balance('5cbd31ab9c93e9280cd36a0a', True) + + :returns: API Response + + .. code-block:: python + + { + "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" + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + # todo check and add the response + + data = { + 'subUserId': sub_user_id, + 'includeBaseAmount': include_base_ammount + } + + return self._get('sub-accounts/{}'.format(sub_user_id), True, data=dict(data, **params)) def get_account(self, account_id): """Get an individual account From b90b94c233ade2e6e5273f10db2b4c119b67c853 Mon Sep 17 00:00:00 2001 From: rayBastard Date: Mon, 4 Nov 2024 17:52:11 +0200 Subject: [PATCH 11/60] get_all_subaccounts_balance and get_all_subaccounts_balance_v2 added --- kucoin/client.py | 123 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 121 insertions(+), 2 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index b244e3b..bc08ce2 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -360,7 +360,7 @@ def get_accounts(self, currency=None, account_type=None, **params): return self._get('accounts', True, data=dict(data, **params)) - def get_subaccounts(self): + def get_subaccounts(self, **params): """Get a list of subaccounts https://www.kucoin.com/docs/rest/account/sub-account/get-all-sub-accounts-info-v1- @@ -452,7 +452,7 @@ def get_subaccounts_v2(self, page=None, limit=None, **params): data['pageSize'] = limit return self._get('sub/user', True, api_version=self.API_VERSION2, data=dict(data, **params)) - + def get_subaccount_balance(self, sub_user_id, include_base_ammount, **params): """Get the account info of a sub-user specified by the subUserId @@ -521,6 +521,125 @@ def get_subaccount_balance(self, sub_user_id, include_base_ammount, **params): return self._get('sub-accounts/{}'.format(sub_user_id), True, data=dict(data, **params)) + def get_all_subaccounts_balance(self): + """Get the account info of all sub-users + + https://www.kucoin.com/docs/rest/account/sub-account/get-all-sub-accounts-balance-v1- + + .. code:: python + + accounts = client.get_all_subaccounts_balance() + + :returns: API Response + + .. code-block:: python + + [ + { + "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" + } + ] + } + ] + + :raises: KucoinResponseException, KucoinAPIException + + """ + # todo check and add the response + + return self._get('sub-accounts', True) + + def get_all_subaccounts_balance_v2(self, page=None, limit=None, **params): + """Get the account info of all sub-users + + https://www.kucoin.com/docs/rest/account/sub-account/get-all-sub-accounts-balance-v2- + + :param page: (optional) Current page - default 1 + :type page: int + :param limit: (optional) Number of results to return - default 10 + :type limit: int + + .. code:: python + + accounts = client.get_all_subaccounts_balance_v2() + accounts = client.get_all_subaccounts_balance_v2(page=2, limit=5) + + :returns: API Response + + .. code-block:: python + + { + "code": "200000", + "data": { + "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" + } + ] + } + ] + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + # todo check and add the response + + data = {} + if page: + data['currentPage'] = page + if limit: + data['pageSize'] = limit + + return self._get('sub-accounts', True, api_version=self.API_VERSION2, data=dict(data, **params)) + def get_account(self, account_id): """Get an individual account From 2b1169b4b8ab80afcd7b6eb55df23789021a1b87 Mon Sep 17 00:00:00 2001 From: rayBastard Date: Mon, 4 Nov 2024 18:32:38 +0200 Subject: [PATCH 12/60] get_subaccount_api_list, create_subaccount_api, modify_subaccount_api, delete_subaccount_api added --- kucoin/client.py | 209 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 209 insertions(+) diff --git a/kucoin/client.py b/kucoin/client.py index bc08ce2..26713a7 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -640,6 +640,215 @@ def get_all_subaccounts_balance_v2(self, page=None, limit=None, **params): return self._get('sub-accounts', True, api_version=self.API_VERSION2, data=dict(data, **params)) + def get_subaccount_api_list(self, , sub_name, api_key=None, **params): + """Get the API key list of a sub-user + + https://www.kucoin.com/docs/rest/account/sub-account-api/get-sub-account-api-list + + :param api_key: (optional) API key + :type api_key: string + :param sub_name: Sub account name + :type sub_name: string + + .. code:: python + + accounts = client.get_subaccount_api_list('kucoin1') + accounts = client.get_subaccount_api_list('kucoin1', '5cbd31ab9c93e9280cd36a0a') + + :returns: API Response + + .. code-block:: python + + { + "code": "200000", + "data": [ + { + "subName": "AAAAAAAAAAAAA0022", + "remark": "hytest01-01", + "apiKey": "63032453e75087000182982b", + "permission": "General", + "ipWhitelist": "", + "createdAt": 1661150291000, + "apiVersion" : 3 + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + # todo check and add the response + + data = { + 'subName': sub_name + } + + if api_key: + data['apiKey'] = api_key + + return self._get('sub/api-key', True, data=dict(data, **params)) + + def create_subaccount_api(self, sub_name, passphrase, remark, permission=None, ip_whitelist=None, expire=None, **params): + """Create Spot APIs for sub-accounts + + https://www.kucoin.com/docs/rest/account/sub-account-api/create-sub-account-api + + :param sub_name: Sub account name + :type sub_name: string + :param passphrase: Sub account passphrase + :type passphrase: string + :param remark: API key remark + :type remark: string + :param permission: (optional) API key permission - General, Tradable, Withdraw + :type permission: string + :param ip_whitelist: (optional) IP whitelist + :type ip_whitelist: string + :param expire: (optional) API key expiration time in seconds + :type expire: string + + .. code:: python + + accounts = client.create_subaccount_api('kucoin1', 'mypassword', 'myApiKey') + + returns: API Response + + .. code-block:: python + + { + "code": "200000", + "data": { + "subName": "AAAAAAAAAA0007", + "remark": "remark", + "apiKey": "630325e0e750870001829864", + "apiSecret": "110f31fc-61c5-4baf-a29f-3f19a62bbf5d", + "passphrase": "passphrase", + "permission": "General", + "ipWhitelist": "", + "createdAt": 1661150688000 + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + # todo check and add the response + + data = { + 'subName': sub_name, + 'passphrase': passphrase, + 'remark': remark + } + + if permission: + data['permission'] = permission + if ip_whitelist: + data['ipWhitelist'] = ip_whitelist + if expire: + data['expire'] = expire + + return self._post('sub/api-key', True, data=dict(data, **params)) + + def modify_subaccount_api(self, sub_name, api_key, passphrase, permission=None, ip_whitelist=None, expire=None, **params): + """Modify Spot APIs for sub-accounts + + https://www.kucoin.com/docs/rest/account/sub-account-api/modify-sub-account-api + + :param sub_name: Sub account name + :type sub_name: string + :param api_key: API key + :type api_key: string + :param passphrase: Sub account passphrase + :type passphrase: string + :param permission: (optional) API key permission - General, Tradable, Withdraw + :type permission: string + :param ip_whitelist: (optional) IP whitelist + :type ip_whitelist: string + :param expire: (optional) API key expiration time in seconds + :type expire: string + + .. code:: python + + accounts = client.modify_subaccount_api('kucoin1', 'myApiKey', 'mypassword') + + returns: API Response + + .. code-block:: python + + { + "code": "200000", + "data": { + "subName": "AAAAAAAAAA0007", + "apiKey": "630329b4e7508700018298c5", + "permission": "General", + "ipWhitelist": "127.0.0.1" + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + # todo check and add the response + + data = { + 'subName': sub_name, + 'apiKey': api_key, + 'passphrase': passphrase + } + + if permission: + data['permission'] = permission + if ip_whitelist: + data['ipWhitelist'] = ip_whitelist + if expire: + data['expire'] = expire + + return self._put('sub/api-key/update', True, data=dict(data, **params)) + + def delete_subaccount_api(self, api_key, passphrase, sub_name, **params): + """Delete Spot APIs for sub-accounts + + https://www.kucoin.com/docs/rest/account/sub-account-api/delete-sub-account-api + + :param api_key: API key + :type api_key: string + :param passphrase: Sub account passphrase + :type passphrase: string + :param sub_name: Sub account name + :type sub_name: string + + .. code:: python + + accounts = client.delete_subaccount_api('myApiKey', 'mypassword', 'kucoin1') + + returns: API Response + + .. code-block:: python + + { + "code": "200000", + "data": { + "subName": "AAAAAAAAAA0007", + "apiKey": "630325e0e750870001829864" + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + # todo check and add the response + + data = { + 'apiKey': api_key, + 'passphrase': passphrase, + 'subName': sub_name + } + + return self._delete('sub/api-key', True, data=dict(data, **params)) + def get_account(self, account_id): """Get an individual account From 461b6e0bc622db8ae2928cfb1f370d135e8ba00a Mon Sep 17 00:00:00 2001 From: rayBastard Date: Mon, 4 Nov 2024 18:46:23 +0200 Subject: [PATCH 13/60] create_deposit_address updated --- kucoin/client.py | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 26713a7..0a5d9af 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -1219,10 +1219,10 @@ def create_inner_transfer(self, currency, from_type, to_type, amount, order_id=N # Deposit Endpoints - def create_deposit_address(self, currency, chain=None): + def create_deposit_address(self, currency, chain=None, **params): """Create deposit address of currency for deposit. You can just create one deposit address. - https://docs.kucoin.com/#create-deposit-address + https://www.kucoin.com/docs/rest/funding/deposit/create-deposit-address :param currency: Name of currency :param chain: The chain name of currency @@ -1231,15 +1231,23 @@ def create_deposit_address(self, currency, chain=None): .. code:: python - address = client.create_deposit_address('NEO') + address = client.create_deposit_address('USDT') + address = client.create_deposit_address('USDT', 'ERC20') :returns: ApiResponse .. code:: python { - "address": "0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1", - "memo": "5c247c8a03aa677cea2a251d" + "data" : { + "memo" : null, + "chain" : "ERC20", + "chainId" : "eth", + "to" : "MAIN", + "currency" : "USDT", + "address" : "0x0a2586d5a901c8e7e68f6b0dc83bfd8bd8600ff5" + }, + "code" : "200000" } :raises: KucoinResponseException, KucoinAPIException @@ -1253,7 +1261,7 @@ def create_deposit_address(self, currency, chain=None): if chain is not None: data['chain'] = chain - return self._post('deposit-addresses', True, data=data) + return self._post('deposit-addresses', True, data=dict(data, **params)) def get_deposit_address(self, currency): """Get deposit address for a currency From 360e6ec2585c11ef96e04a4f9b92ed0980be329d Mon Sep 17 00:00:00 2001 From: rayBastard Date: Mon, 4 Nov 2024 18:58:36 +0200 Subject: [PATCH 14/60] create_deposit_address_v3 added --- kucoin/client.py | 58 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/kucoin/client.py b/kucoin/client.py index 0a5d9af..66c204a 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -1225,8 +1225,8 @@ def create_deposit_address(self, currency, chain=None, **params): https://www.kucoin.com/docs/rest/funding/deposit/create-deposit-address :param currency: Name of currency - :param chain: The chain name of currency :type currency: string + :param chain: (optional) The chain name of currency :type chain: string .. code:: python @@ -1263,6 +1263,62 @@ def create_deposit_address(self, currency, chain=None, **params): return self._post('deposit-addresses', True, data=dict(data, **params)) + def create_deposit_address_v3(self, currency, chain=None, to=None, amount=None, **params): + """Create deposit address for a currency you intend to deposit + + https://www.kucoin.com/docs/rest/funding/deposit/create-deposit-address-v3- + + :param currency: Name of currency + :type currency: string + :param chain: (optional) The chain name of currency + :type chain: string + :param to: (optional) The address that the currency will be sent to + :type to: string + :param amount: (optional) The amount of currency to be deposited + :type amount: string + + .. code:: python + + address = client.create_deposit_address_v3('USDT') + address = client.create_deposit_address_v3('USDT', 'ERC20') + address = client.create_deposit_address_v3('USDT', 'ERC20', '0x0a2586d5a901c8e7e68f6b0dc83bfd8bd8600ff5') + address = client.create_deposit_address_v3('USDT', 'ERC20', '0x0a2586d5a901c8e7e68f6b0dc83bfd8bd8600ff5', 100) + + :returns: ApiResponse + + .. code:: python + + { + "data" : { + "memo" : null, + "chain" : "ERC20", + "chainId" : "eth", + "to" : "MAIN", + "currency" : "USDT", + "address" : "0x0a2586d5a901c8e7e68f6b0dc83bfd8bd8600ff5" + }, + "code" : "200000" + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'currency': currency + } + + if chain is not None: + data['chain'] = chain + + if to is not None: + data['to'] = to + + if amount is not None: + data['amount'] = amount + + return self._post('deposit-address/create', True, api_version=self.API_VERSION3, data=dict(data, **params)) + def get_deposit_address(self, currency): """Get deposit address for a currency From 6b0c8db027b757cacc78ba01ff3b7732185edf7a Mon Sep 17 00:00:00 2001 From: rayBastard Date: Mon, 4 Nov 2024 19:34:59 +0200 Subject: [PATCH 15/60] create_deposit_address and get_deposit_addresses updated --- kucoin/client.py | 140 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 137 insertions(+), 3 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 66c204a..64eaa68 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -1319,17 +1319,20 @@ def create_deposit_address_v3(self, currency, chain=None, to=None, amount=None, return self._post('deposit-address/create', True, api_version=self.API_VERSION3, data=dict(data, **params)) - def get_deposit_address(self, currency): + def get_deposit_address(self, currency, chain=None, **params): """Get deposit address for a currency - https://docs.kucoin.com/#get-deposit-address + https://www.kucoin.com/docs/rest/funding/deposit/get-deposit-address :param currency: Name of currency :type currency: string + :param chain: (optional) The chain name of currency + :type chain: string .. code:: python address = client.get_deposit_address('USDT') + address = client.get_deposit_address('USDT', 'ERC20') :returns: ApiResponse @@ -1349,7 +1352,138 @@ def get_deposit_address(self, currency): 'currency': currency } - return self._get('deposit-addresses', True, api_version=self.API_VERSION2, data=data) + if chain is not None: + data['chain'] = chain + + return self._get('deposit-addresses', True, data=dict(data, **params)) + + def get_deposit_address_v2(self, currency, **params): + """Get deposit address for a currency + + https://www.kucoin.com/docs/rest/funding/deposit/get-deposit-addresses-v2- + + :param currency: Name of currency + :type currency: string + + .. code:: python + + address = client.get_deposit_address_v2('USDT') + + :returns: ApiResponse + + { + "data" : [ + { + "address" : "bc1qwyuvmx53d*****gdg47kqxfwqy", + "chain" : "BTC-Segwit", + "memo" : "", + "contractAddress" : "", + "to" : "MAIN", + "chainId" : "bech32", + "currency" : "BTC" + }, + { + "address" : "3K7X9Vjnd*****TGaTAWoJ7H", + "chain" : "BTC", + "memo" : "", + "contractAddress" : "", + "to" : "MAIN", + "chainId" : "btc", + "currency" : "BTC" + }, + { + "address" : "0x637da22b860*****ac0c2433", + "chain" : "KCC", + "memo" : "", + "contractAddress" : "0xfa93c12cd345c658bc4644d1d4e1b9615952258c", + "to" : "MAIN", + "chainId" : "kcc", + "currency" : "BTC" + } + ], + "code" : "200000" + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'currency': currency + } + + return self._get('deposit-addresses', True, api_version=self.API_VERSION2, data=dict(data, **params)) + + def get_deposit_address_v3(self, currency, amount=None, chain=None, **params): + """Get deposit address for a currency + + https://www.kucoin.com/docs/rest/funding/deposit/get-deposit-addresses-v3- + + :param currency: Name of currency + :type currency: string + :param amount: (optional) The amount of currency to be deposited + :type amount: string + :param chain: (optional) The chain name of currency + :type chain: string + + .. code:: python + + address = client.get_deposit_address_v3('USDT') + address = client.get_deposit_address_v3('USDT', '100') + address = client.get_deposit_address_v3('USDT', '100', 'ERC20') + + :returns: ApiResponse + + .. code:: python + + { + "data" : [ + { + "address" : "bc1qwyuvmx53d*****gdg47kqxfwqy", + "chain" : "BTC-Segwit", + "memo" : "", + "contractAddress" : "", + "to" : "MAIN", + "chainId" : "bech32", + "currency" : "BTC" + }, + { + "address" : "3K7X9Vjnd*****TGaTAWoJ7H", + "chain" : "BTC", + "memo" : "", + "contractAddress" : "", + "to" : "MAIN", + "chainId" : "btc", + "currency" : "BTC" + }, + { + "address" : "0x637da22b860*****ac0c2433", + "chain" : "KCC", + "memo" : "", + "contractAddress" : "0xfa93c12cd345c658bc4644d1d4e1b9615952258c", + "to" : "MAIN", + "chainId" : "kcc", + "currency" : "BTC" + } + ], + "code" : "200000" + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'currency': currency + } + + if amount is not None: + data['amount'] = amount + + if chain is not None: + data['chain'] = chain + + return self._get('deposit-addresses', True, api_version=self.API_VERSION3, data=dict(data, **params)) def get_deposits(self, currency=None, status=None, start=None, end=None, page=None, limit=None): """Get deposit records for a currency From 04ad1e361205a274c9e8002c51754967e701c006 Mon Sep 17 00:00:00 2001 From: rayBastard Date: Mon, 4 Nov 2024 19:41:32 +0200 Subject: [PATCH 16/60] get_deposits updated --- kucoin/client.py | 216 ++++++++--------------------------------------- 1 file changed, 37 insertions(+), 179 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 64eaa68..30c6fb3 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -1219,51 +1219,7 @@ def create_inner_transfer(self, currency, from_type, to_type, amount, order_id=N # Deposit Endpoints - def create_deposit_address(self, currency, chain=None, **params): - """Create deposit address of currency for deposit. You can just create one deposit address. - - https://www.kucoin.com/docs/rest/funding/deposit/create-deposit-address - - :param currency: Name of currency - :type currency: string - :param chain: (optional) The chain name of currency - :type chain: string - - .. code:: python - - address = client.create_deposit_address('USDT') - address = client.create_deposit_address('USDT', 'ERC20') - - :returns: ApiResponse - - .. code:: python - - { - "data" : { - "memo" : null, - "chain" : "ERC20", - "chainId" : "eth", - "to" : "MAIN", - "currency" : "USDT", - "address" : "0x0a2586d5a901c8e7e68f6b0dc83bfd8bd8600ff5" - }, - "code" : "200000" - } - - :raises: KucoinResponseException, KucoinAPIException - - """ - - data = { - 'currency': currency - } - - if chain is not None: - data['chain'] = chain - - return self._post('deposit-addresses', True, data=dict(data, **params)) - - def create_deposit_address_v3(self, currency, chain=None, to=None, amount=None, **params): + def create_deposit_address(self, currency, chain=None, to=None, amount=None, **params): """Create deposit address for a currency you intend to deposit https://www.kucoin.com/docs/rest/funding/deposit/create-deposit-address-v3- @@ -1319,103 +1275,8 @@ def create_deposit_address_v3(self, currency, chain=None, to=None, amount=None, return self._post('deposit-address/create', True, api_version=self.API_VERSION3, data=dict(data, **params)) - def get_deposit_address(self, currency, chain=None, **params): - """Get deposit address for a currency - - https://www.kucoin.com/docs/rest/funding/deposit/get-deposit-address - - :param currency: Name of currency - :type currency: string - :param chain: (optional) The chain name of currency - :type chain: string - - .. code:: python - - address = client.get_deposit_address('USDT') - address = client.get_deposit_address('USDT', 'ERC20') - - :returns: ApiResponse - - .. code:: python - - { - "address": "0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1", - "memo": "5c247c8a03aa677cea2a251d", - "chain": "OMNI" - } - - :raises: KucoinResponseException, KucoinAPIException - - """ - - data = { - 'currency': currency - } - - if chain is not None: - data['chain'] = chain - - return self._get('deposit-addresses', True, data=dict(data, **params)) - - def get_deposit_address_v2(self, currency, **params): - """Get deposit address for a currency - - https://www.kucoin.com/docs/rest/funding/deposit/get-deposit-addresses-v2- - - :param currency: Name of currency - :type currency: string - - .. code:: python - - address = client.get_deposit_address_v2('USDT') - - :returns: ApiResponse - - { - "data" : [ - { - "address" : "bc1qwyuvmx53d*****gdg47kqxfwqy", - "chain" : "BTC-Segwit", - "memo" : "", - "contractAddress" : "", - "to" : "MAIN", - "chainId" : "bech32", - "currency" : "BTC" - }, - { - "address" : "3K7X9Vjnd*****TGaTAWoJ7H", - "chain" : "BTC", - "memo" : "", - "contractAddress" : "", - "to" : "MAIN", - "chainId" : "btc", - "currency" : "BTC" - }, - { - "address" : "0x637da22b860*****ac0c2433", - "chain" : "KCC", - "memo" : "", - "contractAddress" : "0xfa93c12cd345c658bc4644d1d4e1b9615952258c", - "to" : "MAIN", - "chainId" : "kcc", - "currency" : "BTC" - } - ], - "code" : "200000" - } - - :raises: KucoinResponseException, KucoinAPIException - - """ - - data = { - 'currency': currency - } - - return self._get('deposit-addresses', True, api_version=self.API_VERSION2, data=dict(data, **params)) - - def get_deposit_address_v3(self, currency, amount=None, chain=None, **params): - """Get deposit address for a currency + def get_deposit_addresses(self, currency, amount=None, chain=None, **params): + """Get all deposit addresses for the currency you intend to deposit. https://www.kucoin.com/docs/rest/funding/deposit/get-deposit-addresses-v3- @@ -1428,9 +1289,9 @@ def get_deposit_address_v3(self, currency, amount=None, chain=None, **params): .. code:: python - address = client.get_deposit_address_v3('USDT') - address = client.get_deposit_address_v3('USDT', '100') - address = client.get_deposit_address_v3('USDT', '100', 'ERC20') + address = client.get_deposit_addresses('USDT') + address = client.get_deposit_addresses('USDT', '100') + address = client.get_deposit_addresses('USDT', '100', 'ERC20') :returns: ApiResponse @@ -1485,19 +1346,19 @@ def get_deposit_address_v3(self, currency, amount=None, chain=None, **params): return self._get('deposit-addresses', True, api_version=self.API_VERSION3, data=dict(data, **params)) - def get_deposits(self, currency=None, status=None, start=None, end=None, page=None, limit=None): + def get_deposits(self, currency=None, status=None, start=None, end=None, page=None, limit=None, **params): """Get deposit records for a currency - https://docs.kucoin.com/#get-deposit-list + https://www.kucoin.com/docs/rest/funding/deposit/get-deposit-list :param currency: Name of currency (optional) :type currency: string :param status: optional - Status of deposit (PROCESSING, SUCCESS, FAILURE) :type status: string :param start: (optional) Start time as unix timestamp - :type start: string + :type start: int :param end: (optional) End time as unix timestamp - :type end: string + :type end: int :param page: (optional) Page to fetch :type page: int :param limit: (optional) Number of transactions @@ -1506,41 +1367,38 @@ def get_deposits(self, currency=None, status=None, start=None, end=None, page=No .. code:: python deposits = client.get_deposits('NEO') + deposits = client.get_deposits('NEO', 'SUCCESS') + deposits = client.get_deposits('NEO', 'SUCCESS', 1540296039000, 1540296039000) + deposits = client.get_deposits('NEO', 'SUCCESS', 1540296039000, 1540296039000, 1, 5) :returns: ApiResponse .. code:: python { - "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", - "createdAt": 1544178843000, - "updatedAt": 1544178891000 - }, { - "address": "0x5f047b29041bcfdbf0e4478cdfa753a336ba6989", - "memo": "5c247c8a03aa677cea2a251d", - "amount": 1, - "fee": 0.0001, - "currency": "KCS", - "isInner": false, - "walletTxId": "5bbb57386d99522d9f954c5a@test003", - "status": "SUCCESS", - "createdAt": 1544177654000, - "updatedAt": 1544178733000 - } - ] + "code": "200000", + "data": { + "currentPage": 1, + "pageSize": 50, + "totalNum": 1, + "totalPage": 1, + "items": [ + { + "currency": "XRP", + "chain": "xrp", + "status": "SUCCESS", + "address": "rNFugeoj3ZN8Wv6xhuLegUBBPXKCyWLRkB", + "memo": "1919537769", + "isInner": false, + "amount": "20.50000000", + "fee": "0.00000000", + "walletTxId": "2C24A6D5B3E7D5B6AA6534025B9B107AC910309A98825BF5581E25BEC94AD83B", + "createdAt": 1666600519000, + "updatedAt": 1666600549000, + "remark": "Deposit" + } + ] + } } :raises: KucoinResponseException, KucoinAPIException @@ -1561,7 +1419,7 @@ def get_deposits(self, currency=None, status=None, start=None, end=None, page=No if page: data['currentPage'] = page - return self._get('deposits', True, data=data) + return self._get('deposits', True, data=dict(data, **params)) # Withdraw Endpoints From 91b777c810e385f3fa8cd86d5cc120f4b6574c51 Mon Sep 17 00:00:00 2001 From: rayBastard Date: Mon, 4 Nov 2024 19:46:31 +0200 Subject: [PATCH 17/60] get_deposit_history added --- kucoin/client.py | 66 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/kucoin/client.py b/kucoin/client.py index 30c6fb3..1a077bf 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -1421,6 +1421,72 @@ def get_deposits(self, currency=None, status=None, start=None, end=None, page=No return self._get('deposits', True, data=dict(data, **params)) + def get_deposit_history(self, currency=None, status=None, start=None, end=None, page=None, limit=None, **params): + """Get deposit history + + https://www.kucoin.com/docs/rest/funding/deposit/get-v1-historical-deposits-list + + :param currency: Name of currency (optional) + :type currency: string + :param status: optional - Status of deposit (PROCESSING, SUCCESS, FAILURE) + :type status: string + :param start: (optional) Start time as unix timestamp + :type start: string + :param end: (optional) End time as unix timestamp + :type end: string + :param page: (optional) Page to fetch + :type page: int + :param limit: (optional) Number of transactions + :type limit: int + + .. code:: python + + deposits = client.get_deposit_history('NEO') + deposits = client.get_deposit_history('NEO', 'SUCCESS') + deposits = client.get_deposit_history('NEO', 'SUCCESS', 1540296039000, 1540296039000) + deposits = client.get_deposit_history('NEO', 'SUCCESS', 1540296039000, 1540296039000, 1, 5) + + :returns: ApiResponse + + .. code:: python + + { + "currentPage": 1, + "pageSize": 1, + "totalNum": 9, + "totalPage": 9, + "items": [ + { + "currency": "BTC", + "createAt": 1528536998, + "amount": "0.03266638", + "walletTxId": "55c643bc2c68d6f17266383ac1be9e454038864b929ae7cee0bc408cc5c869e8", + "isInner": false, + "status": "SUCCESS" + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + if currency: + data['currency'] = currency + if status: + data['status'] = status + if start: + data['startAt'] = start + if end: + data['endAt'] = end + if limit: + data['pageSize'] = limit + if page: + data['currentPage'] = page + + return self._get('hist-deposits', True, data=dict(data, **params)) + # Withdraw Endpoints def get_withdrawals(self, currency=None, status=None, start=None, end=None, page=None, limit=None): From 3f0fca02329b8d947b2665b6918d1643263571a1 Mon Sep 17 00:00:00 2001 From: rayBastard Date: Mon, 4 Nov 2024 22:02:13 +0200 Subject: [PATCH 18/60] typo fixed --- kucoin/client.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kucoin/client.py b/kucoin/client.py index 1a077bf..17413eb 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -640,7 +640,7 @@ def get_all_subaccounts_balance_v2(self, page=None, limit=None, **params): return self._get('sub-accounts', True, api_version=self.API_VERSION2, data=dict(data, **params)) - def get_subaccount_api_list(self, , sub_name, api_key=None, **params): + def get_subaccount_api_list(self, sub_name, api_key=None, **params): """Get the API key list of a sub-user https://www.kucoin.com/docs/rest/account/sub-account-api/get-sub-account-api-list From b48354e928868b4d461b78ea07eb4e9a4a9f1f8a Mon Sep 17 00:00:00 2001 From: rayBastard Date: Mon, 4 Nov 2024 22:07:47 +0200 Subject: [PATCH 19/60] get_withdrawals updated --- kucoin/client.py | 51 +++++++++++++++++++++++++++--------------------- 1 file changed, 29 insertions(+), 22 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 17413eb..98fdaee 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -1489,10 +1489,10 @@ def get_deposit_history(self, currency=None, status=None, start=None, end=None, # Withdraw Endpoints - def get_withdrawals(self, currency=None, status=None, start=None, end=None, page=None, limit=None): + def get_withdrawals(self, currency=None, status=None, start=None, end=None, page=None, limit=None, **params): """Get deposit records for a currency - https://docs.kucoin.com/#get-withdrawals-list + https://www.kucoin.com/docs/rest/funding/withdrawals/get-withdrawals-list :param currency: Name of currency (optional) :type currency: string @@ -1510,31 +1510,38 @@ def get_withdrawals(self, currency=None, status=None, start=None, end=None, page .. code:: python withdrawals = client.get_withdrawals('NEO') + withdrawals = client.get_withdrawals('NEO', 'SUCCESS') + withdrawals = client.get_withdrawals('NEO', 'SUCCESS', 1540296039000, 1540296039000) :returns: ApiResponse .. code:: python { - "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", - "createdAt": 1546503758000, - "updatedAt": 1546504603000 - } - ] + "code": "200000", + "data": { + "currentPage": 1, + "pageSize": 50, + "totalNum": 1, + "totalPage": 1, + "items": [ + { + "id": "63564dbbd17bef00019371fb", + "currency": "XRP", + "chain": "xrp", + "status": "SUCCESS", + "address": "rNFugeoj3ZN8Wv6xhuLegUBBPXKCyWLRkB", + "memo": "1919537769", + "isInner": false, + "amount": "20.50000000", + "fee": "0.50000000", + "walletTxId": "2C24A6D5B3E7D5B6AA6534025B9B107AC910309A98825BF5581E25BEC94AD83B", + "createdAt": 1666600379000, + "updatedAt": 1666600511000, + "remark": "test" + } + ] + } } :raises: KucoinResponseException, KucoinAPIException @@ -1555,7 +1562,7 @@ def get_withdrawals(self, currency=None, status=None, start=None, end=None, page if page: data['currentPage'] = page - return self._get('withdrawals', True, data=data) + return self._get('withdrawals', True, data=dict(data, **params)) def get_withdrawal_quotas(self, currency): """Get withdrawal quotas for a currency From a8bf600eb8a9c2fbb6cafa9eee48dd700e33e41b Mon Sep 17 00:00:00 2001 From: rayBastard Date: Mon, 4 Nov 2024 22:15:04 +0200 Subject: [PATCH 20/60] get_historical_withdrawals added --- kucoin/client.py | 66 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/kucoin/client.py b/kucoin/client.py index 98fdaee..14411a1 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -1564,6 +1564,72 @@ def get_withdrawals(self, currency=None, status=None, start=None, end=None, page return self._get('withdrawals', True, data=dict(data, **params)) + def get_historical_withdrawals(self, currency=None, status=None, start=None, end=None, page=None, limit=None, **params): + """Get historical withdrawals + + https://www.kucoin.com/docs/rest/funding/withdrawals/get-v1-historical-withdrawals-list + + :param currency: Name of currency (optional) + :type currency: string + :param status: optional - Status of deposit (PROCESSING, SUCCESS, FAILURE) + :type status: string + :param start: (optional) Start time as unix timestamp + :type start: string + :param end: (optional) End time as unix timestamp + :type end: string + :param page: (optional) Page to fetch + :type page: int + :param limit: (optional) Number of transactions + :type limit: int + + .. code:: python + + withdrawals = client.get_historical_withdrawals('NEO') + withdrawals = client.get_historical_withdrawals('NEO', 'SUCCESS') + withdrawals = client.get_historical_withdrawals('NEO', 'SUCCESS', 1540296039000, 1540296039000) + + :returns: ApiResponse + + .. code:: python + + { + "currentPage": 1, + "pageSize": 1, + "totalNum": 2, + "totalPage": 2, + "items": [ + { + "currency": "BTC", + "createAt": 1526723468, + "amount": "0.534", + "address": "33xW37ZSW4tQvg443Pc7NLCAs167Yc2XUV", + "walletTxId": "aeacea864c020acf58e51606169240e96774838dcd4f7ce48acf38e3651323f4", + "isInner": false, + "status": "SUCCESS" + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + if currency: + data['currency'] = currency + if status: + data['status'] = status + if start: + data['startAt'] = start + if end: + data['endAt'] = end + if limit: + data['pageSize'] = limit + if page: + data['currentPage'] = page + + return self._get('hist-withdrawals', True, data=dict(data, **params)) + def get_withdrawal_quotas(self, currency): """Get withdrawal quotas for a currency From a43a479d2c9f9e9e24608cc85701afa1ff017133 Mon Sep 17 00:00:00 2001 From: rayBastard Date: Mon, 4 Nov 2024 22:28:11 +0200 Subject: [PATCH 21/60] get_withdrawal_quotas, create_withdrawal, cancel_withdrawal updated --- kucoin/client.py | 81 ++++++++++++++++++++++++++++++++++-------------- 1 file changed, 57 insertions(+), 24 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 14411a1..d9d70ff 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -1630,13 +1630,15 @@ def get_historical_withdrawals(self, currency=None, status=None, start=None, end return self._get('hist-withdrawals', True, data=dict(data, **params)) - def get_withdrawal_quotas(self, currency): + def get_withdrawal_quotas(self, currency, chain=None, **params): """Get withdrawal quotas for a currency - https://docs.kucoin.com/#get-withdrawal-quotas + https://www.kucoin.com/docs/rest/funding/withdrawals/get-withdrawal-quotas :param currency: Name of currency :type currency: string + :param chain: (optional) The chain name of currency + :type chain: string .. code:: python @@ -1647,15 +1649,24 @@ def get_withdrawal_quotas(self, currency): .. code:: python { - "currency": "ETH", - "availableAmount": 2.9719999, - "remainAmount": 2.9719999, - "withdrawMinSize": 0.1000000, - "limitBTCAmount": 2.0, - "innerWithdrawMinFee": 0.00001, - "isWithdrawEnabled": true, - "withdrawMinFee": 0.0100000, - "precision": 7 + "data": { + "limitBTCAmount": "37.83993375", + "quotaCurrency": "USDT", + "chain": "BTC", + "remainAmount": "37.83993375", + "innerWithdrawMinFee": "0", + "usedBTCAmount": "0.00000000", + "limitQuotaCurrencyAmount": "1000000.00000000", + "withdrawMinSize": "0.0008", + "withdrawMinFee": "0.0005", + "precision": 8, + "reason": null, + "usedQuotaCurrencyAmount": "0", + "currency": "BTC", + "availableAmount": "0", + "isWithdrawEnabled": true + }, + "code": "200000" } :raises: KucoinResponseException, KucoinAPIException @@ -1666,12 +1677,15 @@ def get_withdrawal_quotas(self, currency): 'currency': currency } - return self._get('withdrawals/quotas', True, data=data) + if chain is not None: + data['chain'] = chain + + return self._get('withdrawals/quotas', True, data=dict(data, **params)) - def create_withdrawal(self, currency, amount, address, memo=None, is_inner=False, remark=None): + def create_withdrawal(self, currency, amount, address, withdraw_type, memo=None, is_inner=False, remark=None, chain=None, fee_deduct_type=None, **params): """Process a withdrawal - https://docs.kucoin.com/#apply-withdraw + https://www.kucoin.com/docs/rest/funding/withdrawals/apply-withdraw-v3- :param currency: Name of currency :type currency: string @@ -1679,24 +1693,28 @@ def create_withdrawal(self, currency, amount, address, memo=None, is_inner=False :type amount: number :param address: Address to withdraw to :type address: string + :param withdraw_type: Withdrawal type (ADDRESS (withdrawal address), UID, MAIL (email), PHONE (mobile phone number)) + :type withdraw_type: string :param memo: (optional) Remark to the withdrawal address :type memo: string :param is_inner: (optional) Remark to the withdrawal address :type is_inner: bool :param remark: (optional) Remark :type remark: string + :param chain: (optional) The chain name of currency + :type chain: string + :param fee_deduct_type: (optional) Fee deduct type (INTERNAL or EXTERNAL) + :type fee_deduct_type: string .. code:: python - withdrawal = client.create_withdrawal('NEO', 20, '598aeb627da3355fa3e851') + withdrawal = client.create_withdrawal('NEO', 20, '598aeb627da3355fa3e851', 'ADDRESS') :returns: ApiResponse .. code:: python - { - "withdrawalId": "5bffb63303aa675e8bbe18f9" - } + # todo add response :raises: KucoinResponseException, KucoinAPIException @@ -1705,7 +1723,8 @@ def create_withdrawal(self, currency, amount, address, memo=None, is_inner=False data = { 'currency': currency, 'amount': amount, - 'address': address + 'address': address, + 'withdraw_type': withdraw_type } if memo: @@ -1714,13 +1733,17 @@ def create_withdrawal(self, currency, amount, address, memo=None, is_inner=False data['isInner'] = is_inner if remark: data['remark'] = remark + if chain: + data['chain'] = chain + if fee_deduct_type: + data['feeDeductType'] = fee_deduct_type - return self._post('withdrawals', True, data=data) + return self._post('withdrawals', True, api_version=self.API_VERSION3, data=dict(data, **params)) - def cancel_withdrawal(self, withdrawal_id): + def cancel_withdrawal(self, withdrawal_id, **params): """Cancel a withdrawal - https://docs.kucoin.com/#cancel-withdrawal + https://www.kucoin.com/docs/rest/funding/withdrawals/cancel-withdrawal :param withdrawal_id: ID of withdrawal :type withdrawal_id: string @@ -1729,13 +1752,23 @@ def cancel_withdrawal(self, withdrawal_id): client.cancel_withdrawal('5bffb63303aa675e8bbe18f9') - :returns: None + :returns: ApiResponse + + .. code:: python + + { + "withdrawalId": "5bffb63303aa675e8bbe18f9" + } :raises: KucoinResponseException, KucoinAPIException """ - return self._delete('withdrawals/{}'.format(withdrawal_id), True) + data = { + 'withdrawalId': withdrawal_id + } + + return self._delete('withdrawals/{}'.format(withdrawal_id), True, data=dict(data, **params)) # Order Endpoints From ed768010dd630de9af2039b9f8d7bf369adc8901 Mon Sep 17 00:00:00 2001 From: rayBastard Date: Mon, 4 Nov 2024 23:20:39 +0200 Subject: [PATCH 22/60] transfer endpoints added get_transferable_balance create_universal_transfer create_subaccount_transfer create_inner_transfer create_transfer_out create_transfer_in get_transfer_list --- kucoin/client.py | 355 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 346 insertions(+), 9 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index d9d70ff..a5ef15b 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -1175,25 +1175,190 @@ def get_futures_account_activity(self, currency=None, type=None, start=None, end return self._get('transaction-history', True, dict(data, **params)) - def create_inner_transfer(self, currency, from_type, to_type, amount, order_id=None): + # Transfer Endpoints + + def get_transferable_balance(self, currency, type, tag=None, **params): + """Get transferable balance + + https://www.kucoin.com/docs/rest/funding/transfer/get-the-transferable + + :param currency: currency name + :type currency: string + :param type: Account type: MAIN、TRADE、MARGIN、ISOLATED + :type type: string + :param tag: (optional) Trading pair, required when the account type is ISOLATED; other types are not passed, e.g.: BTC-USDT + :type tag: string + + .. code:: python + + transfer = client.get_transferable_balance('BTC', 'MAIN') + + :returns: API Response + + .. code-block:: python + + { + "currency": "KCS", + "balance": "0", + "available": "0", + "holds": "0", + "transferable": "0" + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'currency': currency, + 'type': type + } + if tag: + data['tag'] = tag + + return self._get('accounts/transferable', True, data=dict(data, **params)) + + def create_universal_transfer(self, client_oid, amount, from_account_type, type, to_account_type, + currency=None, from_user_id=None, from_account_tag=None, to_user_id=None, to_account_tag=None, **params): + """Transfer fund among accounts on the platform + + https://www.kucoin.com/docs/rest/funding/transfer/flextransfer + + :param client_oid: Unique order id created by users to identify their orders, e.g. UUID, with a maximum length of 128 bits + :type client_oid: string + :param amount: Transfer amount, the amount is a positive integer multiple of the currency precision. + :type amount: string + :param from_account_type: Account type:MAIN、TRADE、CONTRACT、MARGIN、ISOLATED、MARGIN_V2、ISOLATED_V2 + :type from_account_type: string + :param type: Transfer type: Transfer type:INTERNAL(Transfer within account)、PARENT_TO_SUB(Transfer from master-account to sub-account),SUB_TO_PARENT(Transfer from sub-account to master-account) + :type type: string + :param to_account_type: Account type:MAIN、TRADE、CONTRACT、MARGIN、ISOLATED、MARGIN_V2、ISOLATED_V2 + :type to_account_type: string + :param currency: (optional) currency name + :type currency: string + :param from_user_id: (optional) Transfer out UserId, This is required when transferring sub-account to master-account. It is optional for internal transfers. + :type from_user_id: string + :param from_account_tag: (optional) Symbol, required when the account type is ISOLATED or ISOLATED_V2, for example: BTC-USDT + :type from_account_tag: string + :param to_user_id: (optional) Transfer in UserId, This is required when transferring master-account to sub-account. It is optional for internal transfers. + :type to_user_id: string + :param to_account_tag: (optional) Symbol, required when the account type is ISOLATED or ISOLATED_V2, for example: BTC-USDT + :type to_account_tag: string + + .. code:: python + + transfer = client.create_universal_transfer('6d539dc614db3', 1, 'MAIN', 'INTERNAL', 'TRADE') + + :returns: API Response + + .. code-block:: python + + { + "clientOid": "64ccc0f164781800010d8c09", + "type": "INTERNAL", + "currency": "BTC", + "amount": 1, + "fromAccountType": "TRADE", + "toAccountType": "CONTRACT" + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'clientOid': client_oid, + 'amount': amount, + 'fromAccountType': from_account_type, + 'type': type, + 'toAccountType': to_account_type + } + if currency: + data['currency'] = currency + if from_user_id: + data['fromUserId'] = from_user_id + if from_account_tag: + data['fromAccountTag'] = from_account_tag + if to_user_id: + data['toUserId'] = to_user_id + if to_account_tag: + data['toAccountTag'] = to_account_tag + + return self._post('accounts/universal-transfer', True, data=dict(data, **params)) + + def create_subaccount_transfer(self, client_oid, currency, amount, direction, sub_user_id, account_type=None, sub_account_type=None, **params): + """Transfer fund from master account to sub-account or from sub-account to master account + + https://www.kucoin.com/docs/rest/funding/transfer/transfer-between-master-account-and-sub-account + + :param client_oid: Unique order id created by users to identify their orders, e.g. UUID, with a maximum length of 128 bits + :type client_oid: string + :param currency: currency name + :type currency: string + :param amount: Transfer amount, the amount is a positive integer multiple of the currency precision. + :type amount: string + :param direction: Transfer direction. OUT — the master user to sub user. IN — the sub user to the master user. + :type direction: string + :param sub_user_id: Sub account user id + :type sub_user_id: string + :param account_type: (optional) The account type of the master user: MAIN, TRADE, MARGIN or CONTRACT, default is MAIN. + :type account_type: string + :param sub_account_type: (optional) The account type of the sub user: MAIN, TRADE, MARGIN or CONTRACT, default is MAIN. + :type sub_account_type: string + + .. code:: python + + transfer = client.create_subaccount_transfer('6d539dc614db3', 'BTC', 1, 'OUT', '5cbd31ab9c93e9280cd36a0a') + + :returns: API Response + + .. code-block:: python + + { + "orderId": "5cbd870fd9575a18e4438b9a" + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'clientOid': client_oid, + 'currency': currency, + 'amount': amount, + 'direction': direction, + 'subUserId': sub_user_id + } + if account_type: + data['accountType'] = account_type + if sub_account_type: + data['subAccountType'] = sub_account_type + + return self._post('accounts/sub-transfer', True, api_version=self.API_VERSION2, data=dict(data, **params)) + + def create_inner_transfer(self, client_oid, currency, from_type, to_type, amount, from_tag=None, to_tag=None, **params): """Transfer fund among accounts on the platform - https://docs.kucoin.com/#inner-transfer + https://www.kucoin.com/docs/rest/funding/transfer/inner-transfer + :param client_oid: Unique order id created by users to identify their orders, e.g. UUID, with a maximum length of 128 bits + :type client_oid: string :param currency: currency name :type currency: str - :param from_type: Account type of payer: main, trade, margin or pool + :param from_type: Payment Account Type: main, trade, margin, isolated, margin_v2, isolated_v2 :type from_type: str - :param to_type: Account type of payee: main, trade, margin , contract or pool + :param to_type: Receiving Account Type: main, trade, margin, isolated, margin_v2, isolated_v2, contract :type to_type: str :param amount: Amount to transfer :type amount: int - :param order_id: (optional) Request ID (default flat_uuid()) - :type order_id: string + :param from_tag: (optional) Symbol, required when the account type is ISOLATED or ISOLATED_V2, for example: BTC-USDT + :type from_tag: str + :param to_tag: (optional) Symbol, required when the account type is ISOLATED or ISOLATED_V2, for example: BTC-USDT + :type to_tag: str .. code:: python - transfer = client.create_inner_transfer('BTC', 'main', 'trade', 1) + transfer = client.create_inner_transfer('6d539dc614db3', 'BTC', 'main', 'trade', 1) :returns: API Response @@ -1208,14 +1373,186 @@ def create_inner_transfer(self, currency, from_type, to_type, amount, order_id=N """ data = { + 'clientOid': client_oid, + 'currency': currency, 'from': from_type, 'to': to_type, + 'amount': amount + } + if from_tag: + data['fromTag'] = from_tag + if to_tag: + data['toTag'] = to_tag + + return self._post('accounts/inner-transfer', True, api_version=self.API_VERSION2, data=dict(data, **params)) + + def create_transfer_out(self, amount, currency, rec_account_type, **params): + """Transfer to Main or TRADE Account + + https://www.kucoin.com/docs/rest/funding/transfer/transfer-to-main-or-trade-account + + :param amount: Transfer amount + :type amount: string + :param currency: Currency + :type currency: string + :param rec_account_type: Receive account type, including MAIN,TRADE + :type rec_account_type: string + + .. code:: python + + transfer = client.create_transfer_out('1', 'BTC', 'TRADE') + + :returns: API Response + + .. code-block:: python + + { + "applyId": "620a0bbefeaa6a000110e833", + "bizNo": "620a0bbefeaa6a000110e832", + "payAccountType": "CONTRACT", + "payTag": "DEFAULT", + "remark": "", + "recAccountType": "MAIN", + "recTag": "DEFAULT", + "recRemark": "", + "recSystem": "KUCOIN", + "status": "PROCESSING", + "currency": "USDT", + "amount": "0.001", + "fee": "0", + "sn": 889048787670001, + "reason": "", + "createdAt": 1644825534000, + "updatedAt": 1644825534000 + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'amount': amount, + 'currency': currency, + 'recAccountType': rec_account_type + } + + return self._post('accounts/transfer-out', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def create_transfer_in(self, amount, currency, pay_account_type, **params): + """Transfer to Futures Account + + https://www.kucoin.com/docs/rest/funding/transfer/transfer-to-futures-account + + :param amount: Transfer amount + :type amount: string + :param currency: Currency + :type currency: string + :param pay_account_type: Pay account type, including MAIN,TRADE + :type pay_account_type: string + + .. code:: python + + transfer = client.create_transfer_in('1', 'BTC', 'TRADE') + + :returns: API Response + + .. code-block:: python + + { + "code": "200", + "msg": "", + "retry": true, + "success": true + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { 'amount': amount, 'currency': currency, - 'clientOid': order_id or flat_uuid(), + 'payAccountType': pay_account_type } - return self._post('accounts/inner-transfer', True, api_version=self.API_VERSION2, data=data) + return self._post('accounts/transfer-in', True, data=dict(data, **params)) + + def get_transfer_list(self, start=None, end=None, status=None, query_status=None, currency=None, page=None, limit=None, **params): + """Get Futures Transfer-Out Request Records + + https://www.kucoin.com/docs/rest/funding/transfer/get-futures-transfer-out-request-records + + :param start: (optional) Start time (milisecond) + :type start: int + :param end: (optional) End time (milisecond) + :type end: int + :param status: (optional) Transfer status: PROCESSING, SUCCESS, FAILURE + :type status: string + :param query_status: (optional) Transfer status: PROCESSING, SUCCESS, FAILURE + :type query_status: string + :param currency: (optional) currency name + :type currency: string + :param page: (optional) Current page - default 1 + :type page: int + :param limit: (optional) Number of results to return - default 50 + :type limit: int + + .. code:: python + + transfer = client.get_transfer_list() + transfer = client.get_transfer_list('1540296039000') + transfer = client.get_transfer_list('1540296039000', '1540296039000') + transfer = client.get_transfer_list('1540296039000', '1540296039000', 'PROCESSING') + transfer = client.get_transfer_list('1540296039000', '1540296039000', 'PROCESSING', 'PROCESSING') + transfer = client.get_transfer_list('1540296039000', '1540296039000', 'PROCESSING', 'PROCESSING', 'BTC') + transfer = client.get_transfer_list('1540296039000', '1540296039000', 'PROCESSING', 'PROCESSING', 'BTC', 1, 10) + + :returns: API Response + + .. code-block:: python + + { + "currentPage": 1, + "pageSize": 50, + "totalNum": 1, + "totalPage": 1, + "items": [ + { + "applyId": "620a0bbefeaa6a000110e833", //Transfer-out request ID + "currency": "USDT", //Currency + "recRemark": "", //Receive account tx remark + "recSystem": "KUCOIN", //Receive system + "status": "SUCCESS", //Status PROCESSING, SUCCESS, FAILURE + "amount": "0.001", //Transaction amount + "reason": "", //Reason caused the failure + "offset": 889048787670001, //Offset + "createdAt": 1644825534000, //Request application time + "remark": "" //User remark + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + if start: + data['startAt'] = start + if end: + data['endAt'] = end + if status: + data['status'] = status + if query_status: + data['queryStatus'] = query_status + if currency: + data['currency'] = currency + if page: + data['currentPage'] = page + if limit: + data['pageSize'] = limit + + return self._get('transfer-list', True, data=dict(data, **params)) # Deposit Endpoints From 08c4e5f832f3306ccd089921eb54091819be7c3c Mon Sep 17 00:00:00 2001 From: rayBastard Date: Mon, 4 Nov 2024 23:34:15 +0200 Subject: [PATCH 23/60] Trade fee endpoints added get_base_fee get_trading_pair_fee futures_get_trading_pair_fee --- kucoin/client.py | 115 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) diff --git a/kucoin/client.py b/kucoin/client.py index a5ef15b..ca17c05 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -2106,6 +2106,121 @@ def cancel_withdrawal(self, withdrawal_id, **params): } return self._delete('withdrawals/{}'.format(withdrawal_id), True, data=dict(data, **params)) + + # Trade Fee Endpoints + + def get_base_fee(self,currency_type=None, **params): + """Get base fee + + https://www.kucoin.com/docs/rest/funding/trade-fee/basic-user-fee-spot-margin-trade_hf + + :param currency_type: (optional) Currency type: 0-crypto currency, 1-fiat currency. default is 0-crypto currency + :type currency_type: string + + .. code:: python + + fee = client.get_base_fee() + fee = client.get_base_fee(1) + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "takerFeeRate": "0.001", + "makerFeeRate": "0.001" + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + if currency_type: + data['currencyType'] = currency_type + + return self._get('base-fee', True, data=dict(data, **params)) + + def get_trading_pair_fee(self, symbols, **params): + """Trading pair actual fee - Spot/Margin/trade_hf + + https://www.kucoin.com/docs/rest/funding/trade-fee/trading-pair-actual-fee-spot-margin-trade_hf + + :param symbols: Trading pair (optional, you can inquire fee rates of 10 trading pairs each time at most) + :type symbols: string + + .. code:: python + + fee = client.get_trading_pair_fee() + fee = client.get_trading_pair_fee('BTC-USDT') + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": [ + { + "symbol": "BTC-USDT", + "takerFeeRate": "0.001", + "makerFeeRate": "0.001" + }, + { + "symbol": "KCS-USDT", + "takerFeeRate": "0.002", + "makerFeeRate": "0.0005" + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + if symbols: + data['symbols'] = symbols + + return self._get('trade-fees', True, data=dict(data, **params)) + + def futures_get_trading_pair_fee(self, symbol, **params): + """Trading pair actual fee - Futures + + https://www.kucoin.com/docs/rest/funding/trade-fee/trading-pair-actual-fee-futures + + :param symbol: Trading pair + :type symbol: string + + .. code:: python + + fee = client.futures_get_trading_pair_fee('ETHUSDTM') + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "symbol": "XBTUSDTM", + "takerFeeRate": "0.0006", + "makerFeeRate": "0.0002" + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('trade-fees', True, data=dict(data, **params)) # Order Endpoints From 9cd7c9573719529934e07deae4830bf7efd63762 Mon Sep 17 00:00:00 2001 From: rayBastard Date: Tue, 5 Nov 2024 00:09:01 +0200 Subject: [PATCH 24/60] Currency endpoints updated get_currencies get_currency --- kucoin/client.py | 159 ++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 129 insertions(+), 30 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index ca17c05..766f09e 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -245,7 +245,7 @@ def get_status(self): def get_currencies(self): """List known currencies - https://docs.kucoin.com/#get-currencies + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-currency-list .. code:: python @@ -255,57 +255,156 @@ def get_currencies(self): .. code-block:: python - [ - { - "currency": "BTC", - "name": "BTC", - "fullName": "Bitcoin", - "precision": 8 - }, - { - "currency": "ETH", - "name": "ETH", - "fullName": "Ethereum", - "precision": 7 - } - ] + { + "code": "200000", + "data": [ + { + "currency": "BTC", + "name": "BTC", + "fullName": "Bitcoin", + "precision": 8, + "confirms": null, + "contractAddress": null, + "isMarginEnabled": true, + "isDebitEnabled": true, + "chains": [ + { + "chainName" : "BTC", + "withdrawalMinFee" : "0.001", + "withdrawalMinSize" : "0.0012", + "withdrawFeeRate" : "0", + "depositMinSize" : "0.0002", + "isWithdrawEnabled" : true, + "isDepositEnabled" : true, + "preConfirms" : 1, + "contractAddress" : "", + "chainId" : "btc", + "confirms" : 3 + }, + { + "chainName" : "KCC", + "withdrawalMinFee" : "0.00002", + "withdrawalMinSize" : "0.0008", + "withdrawFeeRate" : "0", + "depositMinSize" : null, + "isWithdrawEnabled" : true, + "isDepositEnabled" : true, + "preConfirms" : 20, + "contractAddress" : "0xfa93c12cd345c658bc4644d1d4e1b9615952258c", + "chainId" : "kcc", + "confirms" : 20 + }, + { + "chainName" : "BTC-Segwit", + "withdrawalMinFee" : "0.0005", + "withdrawalMinSize" : "0.0008", + "withdrawFeeRate" : "0", + "depositMinSize" : "0.0002", + "isWithdrawEnabled" : false, + "isDepositEnabled" : true, + "preConfirms" : 2, + "contractAddress" : "", + "chainId" : "bech32", + "confirms" : 2 + } + ] + } + ] + } :raises: KucoinResponseException, KucoinAPIException """ - return self._get('currencies', False) + return self._get('currencies', False, api_version=self.API_VERSION3) - def get_currency(self, currency): + def get_currency(self, currency, chain=None, **params): """Get single currency detail - https://docs.kucoin.com/#get-currency-detail + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-currency-detail + + :param currency: Currency code + :type currency: string + :param chain: (optional) Chain name. The available value for USDT are OMNI, ERC20, TRC20. + :type chain: string .. code:: python # call with no coins currency = client.get_currency('BTC') + currency = client.get_currency('BTC', 'ERC20') :returns: API Response .. code-block:: python { - "currency": "BTC", - "name": "BTC", - "fullName": "Bitcoin", - "precision": 8, - "withdrawalMinSize": "0.002", - "withdrawalMinFee": "0.0005", - "isWithdrawEnabled": true, - "isDepositEnabled": true + "data" : { + "isMarginEnabled" : true, + "chains" : [ + { + "chainName" : "BTC", + "withdrawalMinFee" : "0.001", + "withdrawalMinSize" : "0.0012", + "withdrawFeeRate" : "0", + "depositMinSize" : "0.0002", + "isWithdrawEnabled" : true, + "isDepositEnabled" : true, + "preConfirms" : 1, + "contractAddress" : "", + "chainId" : "btc", + "confirms" : 3 + }, + { + "chainName" : "KCC", + "withdrawalMinFee" : "0.00002", + "withdrawalMinSize" : "0.0008", + "withdrawFeeRate" : "0", + "depositMinSize" : null, + "isWithdrawEnabled" : true, + "isDepositEnabled" : true, + "preConfirms" : 20, + "contractAddress" : "0xfa93c12cd345c658bc4644d1d4e1b9615952258c", + "chainId" : "kcc", + "confirms" : 20 + }, + { + "chainName" : "BTC-Segwit", + "withdrawalMinFee" : "0.0005", + "withdrawalMinSize" : "0.0008", + "withdrawFeeRate" : "0", + "depositMinSize" : "0.0002", + "isWithdrawEnabled" : false, + "isDepositEnabled" : true, + "preConfirms" : 2, + "contractAddress" : "", + "chainId" : "bech32", + "confirms" : 2 + } + ], + "contractAddress" : null, + "isDebitEnabled" : true, + "fullName" : "Bitcoin", + "precision" : 8, + "currency" : "BTC", + "name" : "BTC", + "confirms" : null + }, + "code" : "200000" } :raises: KucoinResponseException, KucoinAPIException """ - return self._get('currencies/{}'.format(currency), False) + data = { + 'currency': currency + } + + if chain: + data['chain'] = chain + + return self._get('currencies/{}'.format(currency), False, api_version=self.API_VERSION3, data=dict({'chain': chain}, **params)) # User Account Endpoints @@ -2106,7 +2205,7 @@ def cancel_withdrawal(self, withdrawal_id, **params): } return self._delete('withdrawals/{}'.format(withdrawal_id), True, data=dict(data, **params)) - + # Trade Fee Endpoints def get_base_fee(self,currency_type=None, **params): @@ -2143,7 +2242,7 @@ def get_base_fee(self,currency_type=None, **params): data['currencyType'] = currency_type return self._get('base-fee', True, data=dict(data, **params)) - + def get_trading_pair_fee(self, symbols, **params): """Trading pair actual fee - Spot/Margin/trade_hf @@ -2186,7 +2285,7 @@ def get_trading_pair_fee(self, symbols, **params): data['symbols'] = symbols return self._get('trade-fees', True, data=dict(data, **params)) - + def futures_get_trading_pair_fee(self, symbol, **params): """Trading pair actual fee - Futures From 23560278acb900fed61ac72498e25cf6c30b3b99 Mon Sep 17 00:00:00 2001 From: rayBastard Date: Tue, 5 Nov 2024 00:44:33 +0200 Subject: [PATCH 25/60] market endpoints updated get_symbols get_symbol get_ticker get_tickers get_24hr_stats get_markets get_order_book get_full_order_book get_trade_histories get_kline_data get_fiat_prices --- kucoin/client.py | 363 ++++++++++++++++++++++++++++------------------- 1 file changed, 219 insertions(+), 144 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 766f09e..a8673f2 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -3301,14 +3301,18 @@ def get_fills(self, order_id=None, symbol=None, side=None, order_type=None, # Market Endpoints - def get_symbols(self): + def get_symbols(self, market=None, **params): """Get a list of available currency pairs for trading. - https://docs.kucoin.com/#symbols-amp-ticker + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-symbols-list + + :param market: (optional) Name of market e.g. BTC + :type market: string .. code:: python symbols = client.get_symbols() + symbols = client.get_symbols('USDS') :returns: ApiResponse @@ -3316,17 +3320,41 @@ def get_symbols(self): [ { - "symbol": "BTC-USDT", - "name": "BTC-USDT", - "baseCurrency": "BTC", + "symbol": "XLM-USDT", + "name": "XLM-USDT", + "baseCurrency": "XLM", "quoteCurrency": "USDT", - "baseMinSize": "0.00000001", + "feeCurrency": "USDT", + "market": "USDS", + "baseMinSize": "0.1", "quoteMinSize": "0.01", - "baseMaxSize": "10000", - "quoteMaxSize": "100000", - "baseIncrement": "0.00000001", - "quoteIncrement": "0.01", - "priceIncrement": "0.00000001", + "baseMaxSize": "10000000000", + "quoteMaxSize": "99999999", + "baseIncrement": "0.0001", + "quoteIncrement": "0.000001", + "priceIncrement": "0.000001", + "priceLimitRate": "0.1", + "minFunds": "0.1", + "isMarginEnabled": true, + "enableTrading": true + }, + { + "symbol": "VET-USDT", + "name": "VET-USDT", + "baseCurrency": "VET", + "quoteCurrency": "USDT", + "feeCurrency": "USDT", + "market": "USDS", + "baseMinSize": "10", + "quoteMinSize": "0.01", + "baseMaxSize": "10000000000", + "quoteMaxSize": "99999999", + "baseIncrement": "0.0001", + "quoteIncrement": "0.000001", + "priceIncrement": "0.0000001", + "priceLimitRate": "0.1", + "minFunds": "0.1", + "isMarginEnabled": true, "enableTrading": true } ] @@ -3335,91 +3363,146 @@ def get_symbols(self): """ - return self._get('symbols', False) + data = {} + if market: + data['market'] = market + + return self._get('symbols', False, api_version=self.API_VERSION2, data=dict(data, **params)) - def get_ticker(self, symbol=None): - """Get symbol tick + def get_symbol(self, symbol=None, **params): + """Get a symbol details for trading. - https://docs.kucoin.com/#get-ticker + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-symbol-detail :param symbol: (optional) Name of symbol e.g. KCS-BTC :type symbol: string .. code:: python - all_ticks = client.get_ticker() - - ticker = client.get_ticker('ETH-BTC') + symbol = client.get_symbol('XLM-USDT') :returns: ApiResponse .. code:: python { - "sequence": "1545825031840", # now sequence - "price": "3494.367783", # last trade price - "size": "0.05027185", # last trade size - "bestBid": "3494.367783", # best bid price - "bestBidSize": "2.60323254", # size at best bid price - "bestAsk": "3499.12", # best ask price - "bestAskSize": "0.01474011" # size at best ask price + "data" : { + "quoteMinSize" : "0.1", + "quoteCurrency" : "USDT", + "feeCurrency" : "USDT", + "symbol" : "BTC-USDT", + "market" : "USDS", + "baseMaxSize" : "10000000000", + "baseIncrement" : "0.00000001", + "quoteIncrement" : "0.000001", + "priceIncrement" : "0.1", + "priceLimitRate" : "0.1", + "minFunds" : "0.1", + "isMarginEnabled" : true, + "enableTrading" : true, + "baseCurrency" : "BTC", + "baseMinSize" : "0.00001", + "name" : "BTC-USDT", + "quoteMaxSize" : "99999999" + }, + "code" : "200000" } :raises: KucoinResponseException, KucoinAPIException """ + data = {} - tick_path = 'market/allTickers' - if symbol is not None: - tick_path = 'market/orderbook/level1' - data = { - 'symbol': symbol - } - return self._get(tick_path, False, data=data) + if symbol: + data['symbol'] = symbol - def get_fiat_prices(self, base=None, symbol=None): - """Get fiat price for currency + return self._get('symbol', False, api_version=self.API_VERSION2, data=dict(data, **params)) - https://docs.kucoin.com/#get-fiat-price + def get_ticker(self, symbol, **params): + """Get symbol ticker - :param base: (optional) Fiat,eg.USD,EUR, default is USD. - :type base: string - :param symbol: (optional) Cryptocurrencies.For multiple cyrptocurrencies, please separate them with - comma one by one. default is all + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-ticker + + :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string .. code:: python - prices = client.get_fiat_prices() + ticker = client.get_ticker('ETH-BTC') :returns: ApiResponse .. code:: python { - "BTC": "3911.28000000", - "ETH": "144.55492453", - "LTC": "48.45888179", - "KCS": "0.45546856" + "sequence": "1550467636704", + "price": "0.03715005", + "size": "0.17", + "bestAsk": "0.03715004", + "bestAskSize": "1.788", + "bestBid": "0.03710768", + "bestBidSize": "3.803", + "time": 1550653727731 } :raises: KucoinResponseException, KucoinAPIException """ + data = { + 'symbol': symbol + } + return self._get('market/orderbook/level1', False, data=dict(data, **params)) - data = {} + def get_tickers(self): + """Get symbol tickers - if base is not None: - data['base'] = base - if symbol is not None: - data['currencies'] = symbol + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-all-tickers - return self._get('prices', False, data=data) + .. code:: python - def get_24hr_stats(self, symbol): + tickers = client.get_tickers() + + :returns: ApiResponse + + .. code:: python + + { + "time": 1602832092060, + "ticker": [ + { + "symbol": "BTC-USDT", // symbol + "symbolName": "BTC-USDT", // Name of trading pairs, it would change after renaming + "buy": "11328.9", // bestAsk + "sell": "11329", // bestBid + "bestBidSize": "0.1", + "bestAskSize": "1", + "changeRate": "-0.0055", // 24h change rate + "changePrice": "-63.6", // 24h change price + "high": "11610", // 24h highest price + "low": "11200", // 24h lowest price + "vol": "2282.70993217", // 24h volume,the aggregated trading volume in BTC + "volValue": "25984946.157790431", // 24h total, the trading volume in quote currency of last 24 hours + "last": "11328.9", // last price + "averagePrice": "11360.66065903", // 24h average transaction price yesterday + "takerFeeRate": "0.001", // Basic Taker Fee + "makerFeeRate": "0.001", // Basic Maker Fee + "takerCoefficient": "1", // Taker Fee Coefficient + "makerCoefficient": "1" // Maker Fee Coefficient + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + return self._get('market/allTickers', False) + + def get_24hr_stats(self, symbol, **params): """Get 24hr stats for a symbol. Volume is in base currency units. open, high, low are in quote currency units. - :param symbol: (optional) Name of symbol e.g. KCS-BTC + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-24hr-stats + + :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string .. code:: python @@ -3428,21 +3511,25 @@ def get_24hr_stats(self, symbol): :returns: ApiResponse - Without a symbol param - .. code:: python { - "symbol": "BTC-USDT", - "changeRate": "0.0128", # 24h change rate - "changePrice": "0.8", # 24h rises and falls in price (if the change rate is a negative number, - # the price rises; if the change rate is a positive number, the price falls.) - "open": 61, # Opening price - "close": 63.6, # Closing price - "high": "63.6", # Highest price filled - "low": "61", # Lowest price filled - "vol": "244.78", # Transaction quantity - "volValue": "15252.0127" # Transaction amount + "time": 1602832092060, // time + "symbol": "BTC-USDT", // symbol + "buy": "11328.9", // bestAsk + "sell": "11329", // bestBid + "changeRate": "-0.0055", // 24h change rate + "changePrice": "-63.6", // 24h change price + "high": "11610", // 24h highest price + "low": "11200", // 24h lowest price + "vol": "2282.70993217", // 24h volume the aggregated trading volume in BTC + "volValue": "25984946.157790431", // 24h total, the trading volume in quote currency of last 24 hours + "last": "11328.9", // last price + "averagePrice": "11360.66065903", // 24h average transaction price yesterday + "takerFeeRate": "0.001", // Basic Taker Fee + "makerFeeRate": "0.001", // Basic Maker Fee + "takerCoefficient": "1", // Taker Fee Coefficient + "makerCoefficient": "1" // Maker Fee Coefficient } :raises: KucoinResponseException, KucoinAPIException @@ -3453,12 +3540,12 @@ def get_24hr_stats(self, symbol): 'symbol': symbol } - return self._get('market/stats', False, data=data) + return self._get('market/stats', False, data=dict(data, **params)) def get_markets(self): """Get supported market list - https://docs.kucoin.com/#get-market-list + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-market-list .. code:: python @@ -3470,10 +3557,19 @@ def get_markets(self): { "data": [ + "USDS", //SC has been changed to USDS "BTC", - "ETH", - "USDT" - ] + "KCS", + "ALTS", //ALTS market includes ETH, NEO, TRX + "NFT-ETF", + "FIAT", + "DeFi", + "NFT", + "Metaverse", + "Polkadot", + "ETF" + ], + "code": "200000" } :raises: KucoinResponseException, KucoinAPIException @@ -3481,12 +3577,12 @@ def get_markets(self): """ return self._get('markets', False) - def get_order_book(self, symbol, depth_20=False): + def get_order_book(self, symbol, depth_20=False, **params): """Get a list of bids and asks aggregated by price for a symbol. Returns up to 20 or 100 depth each side. Fastest Order book API - https://docs.kucoin.com/#get-part-order-book-aggregated + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-part-order-book-aggregated- :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string @@ -3503,8 +3599,9 @@ def get_order_book(self, symbol, depth_20=False): { "sequence": "3262786978", + "time": 1550653727731, "bids": [ - ["6500.12", "0.45054140"], # [price, size] + ["6500.12", "0.45054140"], ["6500.11", "0.45054140"] ], "asks": [ @@ -3526,15 +3623,15 @@ def get_order_book(self, symbol, depth_20=False): else: path += '100' - return self._get(path, False, data=data) + return self._get(path, False, data=dict(data, **params)) - def get_full_order_book(self, symbol): + def get_full_order_book(self, symbol, **params): """Get a list of all bids and asks aggregated by price for a symbol. This call is generally used by professional traders because it uses more server resources and traffic, and Kucoin has strict access frequency control. - https://docs.kucoin.com/#get-full-order-book-aggregated + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-full-order-book-aggregated- :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string @@ -3567,69 +3664,12 @@ def get_full_order_book(self, symbol): 'symbol': symbol } - return self._get('market/orderbook/level2', True, api_version=self.API_VERSION3, data=data) - - def get_full_order_book_level3(self, symbol): - """Get a list of all bids and asks non-aggregated for a symbol. - - This call is generally used by professional traders because it uses more server resources and traffic, - and Kucoin has strict access frequency control. - - https://docs.kucoin.com/#get-full-order-book-atomic - - :param symbol: Name of symbol e.g. KCS-BTC - :type symbol: string - - .. code:: python - - orders = client.get_order_book('KCS-BTC') - - :returns: ApiResponse - - .. code:: python - - { - "sequence": "1545896707028", - "bids": [ - [ - "5c2477e503aa671a745c4057", # orderId - "6", # price - "0.999" # size - ], - [ - "5c2477e103aa671a745c4054", - "5", - "0.999" - ] - ], - "asks": [ - [ - "5c24736703aa671a745c401e", - "200", - "1" - ], - [ - "5c2475c903aa671a745c4033", - "201", - "1" - ] - ] - } - - :raises: KucoinResponseException, KucoinAPIException - - """ - - data = { - 'symbol': symbol - } - - return self._get('market/orderbook/level3', False, data=data) + return self._get('market/orderbook/level2', True, api_version=self.API_VERSION3, data=dict(data, **params)) - def get_trade_histories(self, symbol): + def get_trade_histories(self, symbol, **params): """List the latest trades for a symbol - https://docs.kucoin.com/#get-trade-histories + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-trade-histories :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string @@ -3667,11 +3707,13 @@ def get_trade_histories(self, symbol): 'symbol': symbol } - return self._get('market/histories', False, data=data) + return self._get('market/histories', False, data=dict(data, **params)) - def get_kline_data(self, symbol, kline_type='5min', start=None, end=None): + def get_kline_data(self, symbol, kline_type='5min', start=None, end=None, **params): """Get kline data + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-klines + For each query, the system would return at most 1500 pieces of data. To obtain more data, please page the data by time. @@ -3685,8 +3727,6 @@ def get_kline_data(self, symbol, kline_type='5min', start=None, end=None): :param end: End time as unix timestamp (optional) default now in UTC :type end: int - https://docs.kucoin.com/#get-historic-rates - .. code:: python klines = client.get_kline_data('KCS-BTC', '5min', 1507479171, 1510278278) @@ -3728,14 +3768,49 @@ def get_kline_data(self, symbol, kline_type='5min', start=None, end=None): data['type'] = kline_type if start is not None: data['startAt'] = start - else: - data['startAt'] = calendar.timegm(datetime.utcnow().date().timetuple()) if end is not None: data['endAt'] = end - else: - data['endAt'] = int(time.time()) - return self._get('market/candles', False, data=data) + return self._get('market/candles', False, data=dict(data, **params)) + + def get_fiat_prices(self, base=None, currencies=None, **params): + """Get fiat price for currency + + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-fiat-price + + :param base: (optional) Fiat,eg.USD,EUR, default is USD. + :type base: string + :param currencies: (optional) Cryptocurrencies.For multiple cyrptocurrencies, please separate them with + comma one by one. default is all + :type currencies: string + + .. code:: python + + prices = client.get_fiat_prices() + + :returns: ApiResponse + + .. code:: python + + { + "BTC": "3911.28000000", + "ETH": "144.55492453", + "LTC": "48.45888179", + "KCS": "0.45546856" + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + + if base is not None: + data['base'] = base + if currencies is not None: + data['currencies'] = currencies + + return self._get('prices', False, data=dict(data, **params)) # Websocket Endpoints From eb966cd701282abfc1b93ca81d5594db61e7fbc0 Mon Sep 17 00:00:00 2001 From: yzh-pelle <81404729+yzh-pelle@users.noreply.github.com> Date: Tue, 5 Nov 2024 14:52:23 +0300 Subject: [PATCH 26/60] get_announcements added --- kucoin/client.py | 75 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 73 insertions(+), 2 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index a8673f2..2665e89 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -213,7 +213,7 @@ def _delete(self, path, signed=False, api_version=None, **kwargs): def get_timestamp(self): """Get the server timestamp - https://docs.kucoin.com/#time + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-server-time :return: response timestamp in ms @@ -223,7 +223,7 @@ def get_timestamp(self): def get_status(self): """Get the service status - https://docs.kucoin.com/#service-status + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-service-status .. code:: python @@ -240,6 +240,77 @@ def get_status(self): """ return self._get("status") + def get_announcements(self, page=None, limit=None, ann_type=None, lang=None, start=None, end=None, **params): + """Get a list of the latest news announcements + + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-announcements + + :param page: (optional) Current page + :type page: int + :param limit: (optional) Number of results to return + :type limit: int + :param ann_type: (optional) Announcement type: latest-announcements, activities, new-listings, product-updates, vip, maintenance-updates, product-updates, delistings, others, api-campaigns (default latest-announcements) + :type ann_type: string + :param lang: (optional) Language (default is en_US): zh_HK - Chinese (Hong Kong), ja_JP - Japanese (Japan), ko_KR - Korean (Korea), en_US - English, pl_PL - Polish (Poland), es_ES - Spanish (Spain), fr_FR - French (France), ar_AE - Arabic (Egypt), it_IT - Italian (Italy), id_ID - Indonesian (Indonesia), nl_NL - Dutch (Netherlands), pt_PT - Portuguese (Brazil), vi_VN - Vietnamese (Vietnam), de_DE - German (Germany), tr_TR - Turkish (Turkey), ms_MY - Malay (Malaysia), ru_RU - Russian (Russia), th_TH - Thai (Thailand), hi_IN - Hindi (India), bn_BD - Bengali (Bangladesh), fil_PH - Filipino (Philippines), ur_PK - Urdu (Pakistan). + :type lang: string + :param start: (optional) Start time as unix timestamp + :type start: string + :param end: (optional) End time as unix timestamp + :type end: string + + .. code:: python + + accounts = client.get_announcements() + accounts = client.get_announcements(page=2, lang='ja_JP') + + :returns: API Response + + .. code-block:: python + + { + "code": "200000", + "data": { + "totalNum": 198, + "items": [ + { + "annId": 131185, + "annTitle": "Announcement of KuCoin Futures System Upgrade", + "annType": [ + "latest-announcements", + "futures-announcements" + ], + "annDesc": "Announcement of KuCoin Futures System Upgrade", + "cTime": 1730798882000, + "language": "en_US", + "annUrl": "https://www.kucoin.com/announcement/announcement-of-kucoin-futures-system-upgrade-2024-11-11?lang=en_US" + } + ], + "currentPage": 2, + "pageSize": 1, + "totalPage": 198 + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + if page: + data['currentPage'] = page + if limit: + data['pageSize'] = limit + if ann_type: + data['annType'] = ann_type + if lang: + data['lang'] = lang + if start: + data['startTime'] = start + if end: + data['endTime'] = end + + return self._get('announcements', False, api_version=self.API_VERSION3, data=dict(data, **params)) + # Currency Endpoints def get_currencies(self): From 494a592663b511a65ff819a1749e12bc4f0d7069 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Tue, 5 Nov 2024 15:34:28 +0300 Subject: [PATCH 27/60] get_user_type added --- kucoin/client.py | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 2665e89..8c408c9 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -44,8 +44,8 @@ class Client(object): TIMEINFORCE_IMMEDIATE_OR_CANCEL = 'IOC' TIMEINFORCE_FILL_OR_KILL = 'FOK' - SPOT_KC_PARTNER = 'python-kucoinspot' - SPOT_KC_KEY = '922783d1-067e-4a31-bb42-4d1589624e30' + SPOT_KC_PARTNER = 'ccxt' # todo handle with standard python-kucoin signature + SPOT_KC_KEY = '9e58cc35-5b5e-4133-92ec-166e3f077cb8' def __init__(self, api_key, api_secret, passphrase, sandbox=False, requests_params=None): """Kucoin API Client constructor @@ -1994,6 +1994,30 @@ def get_deposit_history(self, currency=None, status=None, start=None, end=None, return self._get('hist-deposits', True, data=dict(data, **params)) + def get_user_type(self, **params): + """Get user type (the current user is a spot high-frequency user or a spot low-frequency user) + + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/get-user-type + + .. code:: python + + deposits = client.get_user_type() + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": true // true: high-frequency user, false: low-frequency user + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + return self._get('hf/accounts/opened', True, data=params) + # Withdraw Endpoints def get_withdrawals(self, currency=None, status=None, start=None, end=None, page=None, limit=None, **params): From 3d7c95cc94a210772fbf00d519fcaf830a47c71a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Tue, 5 Nov 2024 17:09:16 +0300 Subject: [PATCH 28/60] hf_create_order added --- kucoin/client.py | 120 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 105 insertions(+), 15 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 8c408c9..4a8b31c 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -44,8 +44,11 @@ class Client(object): TIMEINFORCE_IMMEDIATE_OR_CANCEL = 'IOC' TIMEINFORCE_FILL_OR_KILL = 'FOK' - SPOT_KC_PARTNER = 'ccxt' # todo handle with standard python-kucoin signature - SPOT_KC_KEY = '9e58cc35-5b5e-4133-92ec-166e3f077cb8' + # SPOT_KC_PARTNER = 'ccxt' # todo handle with standard python-kucoin signature + # SPOT_KC_KEY = '9e58cc35-5b5e-4133-92ec-166e3f077cb8' + + SPOT_KC_PARTNER = 'python-kucoinspot' + SPOT_KC_KEY = '922783d1-067e-4a31-bb42-4d1589624e30' def __init__(self, api_key, api_secret, passphrase, sandbox=False, requests_params=None): """Kucoin API Client constructor @@ -73,7 +76,7 @@ def __init__(self, api_key, api_secret, passphrase, sandbox=False, requests_para self.API_SECRET = api_secret self.API_PASSPHRASE = passphrase if sandbox: - self.API_URL = self.SANDBOX_API_URL + self.API_URL = self.SANDBOX_API_URL # todo handle with new sandbox url else: self.API_URL = self.REST_API_URL @@ -567,7 +570,7 @@ def get_subaccounts(self, **params): """ # todo check and add the response - return self._get('sub/user', True) + return self._get('sub/user', True, data=params) def get_subaccounts_v2(self, page=None, limit=None, **params): """Get a list of subaccounts @@ -2446,7 +2449,7 @@ def create_market_order( .. code:: python - order = client.create_market_order('NEO', Client.SIDE_BUY, size=20) + order = client.create_market_order('ETH-USDT', Client.SIDE_BUY, size=20) :returns: ApiResponse @@ -2489,9 +2492,96 @@ def create_market_order( return self._post('orders', True, data=data) - def hf_create_market_order( - self, symbol, side, size=None, funds=None, client_oid=None, stp=None, tags=None, remark=None - ): + def hf_create_order (self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, + tags=None, remark=None, time_in_force=None, cancel_after=None, post_only=None, + hidden=None, iceberg=None, visible_size=None, **params): + """Create a hf order + + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/place-hf-order + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param type: order type (limit or market) + :type type: string + :param side: buy or sell + :type side: string + :param size: (optional) Desired amount in base currency (required for limit order) + :type size: string + :param price: (optional) Price (required for limit order) + :type price: string + :param funds: (optional) Desired amount of quote currency to use (for market order only) + :type funds: string + :param client_oid: (optional) Unique order id (default flat_uuid()) + :type client_oid: string + :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) + :type stp: string + :param tags: (optional) order tag, length cannot exceed 20 characters (ASCII) + :type tags: string + :param remark: (optional) remark for the order, max 100 utf8 characters + :type remark: string + :param time_in_force: (optional) GTC, GTT, IOC, or FOK - default is GTC (for limit order only) + :type time_in_force: string + :param cancel_after: (optional) time in ms to cancel after (for limit order only) + :type cancel_after: string + :param post_only: (optional) Post only flag (for limit order only) + :type post_only: bool + :param hidden: (optional) Hidden order flag (for limit order only) + :type hidden: bool + :param iceberg: (optional) Iceberg order flag (for limit order only) + :type iceberg: bool + :param visible_size: (optional) The maximum visible size of an iceberg order (for limit orders only) + :type visible_size: string + + .. code:: python + + order = client.hf_create_order('ETH-USDT', Client.ORDER_LIMIT, Client.SIDE_BUY, size=20, price=2000) + order = client.hf_create_order('ETH-USDT', Client.ORDER_MARKET, Client.SIDE_BUY, funds=20) + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "orderId": "672a249054d62a0007ae04b8", + "clientOid": "988a99edda5e496e95eb6e050c444994" + } + } + + :raises: KucoinResponseException, KucoinAPIException, MarketOrderException, LimitOrderException, KucoinRequestException + + """ + + if type == self.ORDER_LIMIT: + if not price: + raise LimitOrderException('Need price parameter for limit order') + if funds: + raise LimitOrderException('Cannot use funds parameter with limit order') + return self.hf_create_limit_order(symbol, side, price, size, client_oid, stp, + tags, remark, time_in_force, cancel_after, post_only, + hidden, iceberg, visible_size, **params) + elif type == self.ORDER_MARKET: + if price: + raise MarketOrderException('Cannot use price parameter with market order') + if time_in_force: + raise MarketOrderException('Cannot use time_in_force parameter with market order') + if cancel_after: + raise MarketOrderException('Cannot use cancel_after parameter with market order') + if post_only: + raise MarketOrderException('Cannot use post_only parameter with market order') + if hidden: + raise MarketOrderException('Cannot use hidden parameter with market order') + if iceberg: + raise MarketOrderException('Cannot use iceberg parameter with market order') + if visible_size: + raise MarketOrderException('Cannot use visible_size parameter with market order') + return self.hf_create_market_order(symbol, side, size, funds, client_oid, stp, tags, remark) + else: + raise KucoinRequestException('Invalid order type {}'.format(type)) + + def hf_create_market_order(self, symbol, side, size=None, funds=None, client_oid=None, + stp=None, tags=None, remark=None, **params): """Create a hf market order One of size or funds must be set @@ -2517,7 +2607,7 @@ def hf_create_market_order( .. code:: python - order = client.hf_create_market_order('NEO', Client.SIDE_BUY, size=20) + order = client.hf_create_market_order('ETH-USDT', Client.SIDE_BUY, size=20) :returns: ApiResponse @@ -2562,13 +2652,13 @@ def hf_create_market_order( if remark: data['remark'] = remark - return self._post('hf/orders', True, data=data) + return self._post('hf/orders', True, data=dict(data, **params)) def create_limit_order(self, symbol, side, price, size, client_oid=None, remark=None, time_in_force=None, stop=None, stop_price=None, stp=None, trade_type=None, cancel_after=None, post_only=None, hidden=None, iceberg=None, visible_size=None): - """Create an order + """Create a limit order https://docs.kucoin.com/#place-a-new-order @@ -2605,7 +2695,7 @@ def create_limit_order(self, symbol, side, price, size, client_oid=None, remark= :param iceberg: (optional) Only visible portion of the order is displayed in the order book :type iceberg: bool :param visible_size: (optional) The maximum visible size of an iceberg order - :type visible_size: bool + :type visible_size: string .. code:: python @@ -2675,8 +2765,8 @@ def create_limit_order(self, symbol, side, price, size, client_oid=None, remark= def hf_create_limit_order(self, symbol, side, price, size, client_oid=None, stp=None, tags=None, remark=None, time_in_force=None, cancel_after=None, post_only=None, - hidden=None, iceberg=None, visible_size=None): - """Create a hf order + hidden=None, iceberg=None, visible_size=None, **params): + """Create a hf limit order https://docs.kucoin.com/#place-hf-order @@ -2770,7 +2860,7 @@ def hf_create_limit_order(self, symbol, side, price, size, client_oid=None, stp= data['iceberg'] = iceberg data['visible_size'] = visible_size - return self._post('hf/orders', True, data=data) + return self._post('hf/orders', True, data=dict(data, **params)) def cancel_order(self, order_id): """Cancel an order From 05977ff341df0e4ea6685d80bda629528c869876 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Tue, 5 Nov 2024 21:03:24 +0300 Subject: [PATCH 29/60] client.py updated --- kucoin/client.py | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 4a8b31c..fd11cc2 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -15,7 +15,7 @@ class Client(object): REST_API_URL = 'https://openapi-v2.kucoin.com' - SANDBOX_API_URL = 'https://openapi-sandbox.kucoin.com' + # SANDBOX_API_URL = 'https://openapi-sandbox.kucoin.com' #does not supported anymore API_VERSION = 'v1' API_VERSION2 = 'v2' API_VERSION3 = 'v3' @@ -76,7 +76,7 @@ def __init__(self, api_key, api_secret, passphrase, sandbox=False, requests_para self.API_SECRET = api_secret self.API_PASSPHRASE = passphrase if sandbox: - self.API_URL = self.SANDBOX_API_URL # todo handle with new sandbox url + raise KucoinAPIException('Sandbox mode is not supported anymore. See https://www.kucoin.com/docs/beginners/sandbox. To test orders, use test methods (e.g. create_test_order)') else: self.API_URL = self.REST_API_URL @@ -2421,9 +2421,8 @@ def futures_get_trading_pair_fee(self, symbol, **params): # Order Endpoints - def create_market_order( - self, symbol, side, size=None, funds=None, client_oid=None, remark=None, stp=None, trade_type=None - ): + def create_market_order(self, symbol, side, size=None, funds=None, client_oid=None, + remark=None, stp=None, **params): """Create a market order One of size or funds must be set @@ -2487,10 +2486,8 @@ def create_market_order( data['remark'] = remark if stp: data['stp'] = stp - if trade_type: - data['tradeType'] = trade_type - return self._post('orders', True, data=data) + return self._post('orders', True, data=dict(data, **params)) def hf_create_order (self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, tags=None, remark=None, time_in_force=None, cancel_after=None, post_only=None, From 8f0bb445fe4447e67093eb28404d88275cf70c5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Thu, 7 Nov 2024 18:14:20 +0300 Subject: [PATCH 30/60] hf_create_order, hf_create_limit_order and hf_create_market_order updated --- kucoin/client.py | 202 +++++++++++++++++++++++------------------------ 1 file changed, 99 insertions(+), 103 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index fd11cc2..9472126 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -28,8 +28,8 @@ class Client(object): ORDER_LIMIT = 'limit' ORDER_MARKET = 'market' - ORDER_LIMIT_STOP = 'limit_stop' - ORDER_MARKET_STOP = 'market_stop' + ORDER_LIMIT_STOP = 'limit_stop' # todo handle with new interface + ORDER_MARKET_STOP = 'market_stop' # todo handle with new interface STOP_LOSS = 'loss' STOP_ENTRY = 'entry' @@ -2421,6 +2421,83 @@ def futures_get_trading_pair_fee(self, symbol, **params): # Order Endpoints + def get_common_data_for_order(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, + stp=None, remark=None, time_in_force=None, cancel_after=None, post_only=None, + hidden=None, iceberg=None, visible_size=None): + + """Internal helper for creating a common data for order""" + + data = { + 'symbol': symbol, + 'type': type, + 'side': side + } + + if type == self.ORDER_MARKET: + if not size and not funds: + raise MarketOrderException('Need size or fund parameter') + if size and funds: + raise MarketOrderException('Need size or fund parameter not both') + if size: + data['size'] = size + if funds: + data['funds'] = funds + if price: + raise MarketOrderException('Cannot use price parameter with market order') + if time_in_force: + raise MarketOrderException('Cannot use time_in_force parameter with market order') + if cancel_after: + raise MarketOrderException('Cannot use cancel_after parameter with market order') + if post_only: + raise MarketOrderException('Cannot use post_only parameter with market order') + if hidden: + raise MarketOrderException('Cannot use hidden parameter with market order') + if iceberg: + raise MarketOrderException('Cannot use iceberg parameter with market order') + if visible_size: + raise MarketOrderException('Cannot use visible_size parameter with market order') + + elif type == self.ORDER_LIMIT: + if not price: + raise LimitOrderException('Need price parameter for limit order') + if funds: + raise LimitOrderException('Cannot use funds parameter with limit order') + if not size: + raise LimitOrderException('Need size parameter for limit order') + if cancel_after and time_in_force != self.TIMEINFORCE_GOOD_TILL_TIME: + raise LimitOrderException('Cancel after only works with time_in_force = "GTT"') + if hidden and iceberg: + raise LimitOrderException('Order can be either "hidden" or "iceberg"') + if iceberg and not visible_size: + raise LimitOrderException('Iceberg order requires visible_size') + data['size'] = size + data['price'] = price + if time_in_force: + data['timeInForce'] = time_in_force + if cancel_after: + data['cancelAfter'] = cancel_after + if post_only: + data['postOnly'] = post_only + if hidden: + data['hidden'] = hidden + if iceberg: + data['iceberg'] = iceberg + if visible_size: + data['visibleSize'] = visible_size + + elif (type == self.ORDER_LIMIT_STOP or type == self.ORDER_MARKET_STOP): + raise KucoinRequestException('Invalid order type {}. Possible types are {} and {}. To create a stop order please use create_stop_order()'.format(type, self.ORDER_LIMIT, self.ORDER_MARKET)) + else: + raise KucoinRequestException('Invalid order type {}. Possible types are {} and {}'.format(type, self.ORDER_LIMIT, self.ORDER_MARKET)) + + if client_oid: + data['clientOid'] = client_oid #todo check if it is mandatory + if stp: + data['stp'] = stp + if remark: + data['remark'] = remark + return data + def create_market_order(self, symbol, side, size=None, funds=None, client_oid=None, remark=None, stp=None, **params): """Create a market order @@ -2490,9 +2567,9 @@ def create_market_order(self, symbol, side, size=None, funds=None, client_oid=No return self._post('orders', True, data=dict(data, **params)) def hf_create_order (self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, - tags=None, remark=None, time_in_force=None, cancel_after=None, post_only=None, - hidden=None, iceberg=None, visible_size=None, **params): - """Create a hf order + remark=None, time_in_force=None, cancel_after=None, post_only=None, + hidden=None, iceberg=None, visible_size=None, tags=None, **params): + """Create a hf spot order https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/place-hf-order @@ -2550,36 +2627,18 @@ def hf_create_order (self, symbol, type, side, size=None, price=None, funds=None """ - if type == self.ORDER_LIMIT: - if not price: - raise LimitOrderException('Need price parameter for limit order') - if funds: - raise LimitOrderException('Cannot use funds parameter with limit order') - return self.hf_create_limit_order(symbol, side, price, size, client_oid, stp, - tags, remark, time_in_force, cancel_after, post_only, - hidden, iceberg, visible_size, **params) - elif type == self.ORDER_MARKET: - if price: - raise MarketOrderException('Cannot use price parameter with market order') - if time_in_force: - raise MarketOrderException('Cannot use time_in_force parameter with market order') - if cancel_after: - raise MarketOrderException('Cannot use cancel_after parameter with market order') - if post_only: - raise MarketOrderException('Cannot use post_only parameter with market order') - if hidden: - raise MarketOrderException('Cannot use hidden parameter with market order') - if iceberg: - raise MarketOrderException('Cannot use iceberg parameter with market order') - if visible_size: - raise MarketOrderException('Cannot use visible_size parameter with market order') - return self.hf_create_market_order(symbol, side, size, funds, client_oid, stp, tags, remark) - else: - raise KucoinRequestException('Invalid order type {}'.format(type)) + data = self.get_common_data_for_order(symbol, type, side, size, price, funds, client_oid, stp, remark, + time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) + + if tags: + data['tags'] = tags + + return self._post('hf/orders', True, data=dict(data, **params)) + def hf_create_market_order(self, symbol, side, size=None, funds=None, client_oid=None, stp=None, tags=None, remark=None, **params): - """Create a hf market order + """Create a hf spot market order One of size or funds must be set @@ -2622,34 +2681,8 @@ def hf_create_market_order(self, symbol, side, size=None, funds=None, client_oid """ - if not size and not funds: - raise MarketOrderException('Need size or fund parameter') - - if size and funds: - raise MarketOrderException('Need size or fund parameter not both') - - data = { - 'symbol': symbol, - 'side': side, - 'type': self.ORDER_MARKET - } - - if size: - data['size'] = size - if funds: - data['funds'] = funds - if client_oid: - data['clientOid'] = client_oid - else: - data['clientOid'] = flat_uuid() - if stp: - data['stp'] = stp - if tags: - data['tags'] = tags - if remark: - data['remark'] = remark - - return self._post('hf/orders', True, data=dict(data, **params)) + return self.hf_create_order(symbol, self.ORDER_MARKET, side, size, funds=funds, client_oid=client_oid, + stp=stp, remark=remark, tags=tags, **params) def create_limit_order(self, symbol, side, price, size, client_oid=None, remark=None, time_in_force=None, stop=None, stop_price=None, stp=None, trade_type=None, @@ -2761,9 +2794,9 @@ def create_limit_order(self, symbol, side, price, size, client_oid=None, remark= return self._post('orders', True, data=data) def hf_create_limit_order(self, symbol, side, price, size, client_oid=None, stp=None, - tags=None, remark=None, time_in_force=None, cancel_after=None, post_only=None, - hidden=None, iceberg=None, visible_size=None, **params): - """Create a hf limit order + remark=None, time_in_force=None, cancel_after=None, post_only=None, + hidden=None, iceberg=None, visible_size=None, tags=None, **params): + """Create a hf spot limit order https://docs.kucoin.com/#place-hf-order @@ -2818,46 +2851,9 @@ def hf_create_limit_order(self, symbol, side, price, size, client_oid=None, stp= """ - if cancel_after and time_in_force != self.TIMEINFORCE_GOOD_TILL_TIME: - raise LimitOrderException('Cancel after only works with time_in_force = "GTT"') - - if hidden and iceberg: - raise LimitOrderException('Order can be either "hidden" or "iceberg"') - - if iceberg and not visible_size: - raise LimitOrderException('Iceberg order requires visible_size') - - data = { - 'symbol': symbol, - 'side': side, - 'type': self.ORDER_LIMIT, - 'price': price, - 'size': size - } - - if client_oid: - data['clientOid'] = client_oid - else: - data['clientOid'] = flat_uuid() - if stp: - data['stp'] = stp - if tags: - data['tags'] = tags - if remark: - data['remark'] = remark - if time_in_force: - data['timeInForce'] = time_in_force - if cancel_after: - data['cancelAfter'] = cancel_after - if post_only: - data['postOnly'] = post_only - if hidden: - data['hidden'] = hidden - if iceberg: - data['iceberg'] = iceberg - data['visible_size'] = visible_size - - return self._post('hf/orders', True, data=dict(data, **params)) + return self.hf_create_order(symbol, self.ORDER_LIMIT, side, size, price=price, client_oid=client_oid, + stp=stp, remark=remark, time_in_force=time_in_force, cancel_after=cancel_after, + post_only=post_only, hidden=hidden, iceberg=iceberg, visible_size=visible_size, tags=tags, **params) def cancel_order(self, order_id): """Cancel an order From efe37178e87764c840cc178372c06a3fa1e942cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Thu, 7 Nov 2024 19:40:21 +0300 Subject: [PATCH 31/60] create_order added --- kucoin/client.py | 297 ++++++++++++++++++++++++----------------------- 1 file changed, 149 insertions(+), 148 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 9472126..630b258 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -15,7 +15,7 @@ class Client(object): REST_API_URL = 'https://openapi-v2.kucoin.com' - # SANDBOX_API_URL = 'https://openapi-sandbox.kucoin.com' #does not supported anymore + # SANDBOX_API_URL = 'https://openapi-sandbox.kucoin.com' # does not supported anymore API_VERSION = 'v1' API_VERSION2 = 'v2' API_VERSION3 = 'v3' @@ -28,8 +28,8 @@ class Client(object): ORDER_LIMIT = 'limit' ORDER_MARKET = 'market' - ORDER_LIMIT_STOP = 'limit_stop' # todo handle with new interface - ORDER_MARKET_STOP = 'market_stop' # todo handle with new interface + ORDER_LIMIT_STOP = 'limit_stop' # deprecated + ORDER_MARKET_STOP = 'market_stop' # deprecated STOP_LOSS = 'loss' STOP_ENTRY = 'entry' @@ -2424,7 +2424,6 @@ def futures_get_trading_pair_fee(self, symbol, **params): def get_common_data_for_order(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, remark=None, time_in_force=None, cancel_after=None, post_only=None, hidden=None, iceberg=None, visible_size=None): - """Internal helper for creating a common data for order""" data = { @@ -2498,13 +2497,85 @@ def get_common_data_for_order(self, symbol, type, side, size=None, price=None, f data['remark'] = remark return data + def create_order(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, + remark=None, time_in_force=None, cancel_after=None, post_only=None, + hidden=None, iceberg=None, visible_size=None, trade_type=None, **params): + """Create a spot order + + https://www.kucoin.com/docs/rest/spot-trading/orders/place-order + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param type: order type (limit or market) + :type type: string + :param side: buy or sell + :type side: string + :param size: (optional) Desired amount in base currency (required for limit order) + :type size: string + :param price: (optional) Price (required for limit order) + :type price: string + :param funds: (optional) Desired amount of quote currency to use (for market order only) + :type funds: string + :param client_oid: (optional) Unique order id (default flat_uuid()) + :type client_oid: string + :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) + :type stp: string + :param remark: (optional) remark for the order, max 100 utf8 characters + :type remark: string + :param time_in_force: (optional) GTC, GTT, IOC, or FOK - default is GTC (for limit order only) + :type time_in_force: string + :param cancel_after: (optional) time in ms to cancel after (for limit order only) + :type cancel_after: string + :param post_only: (optional) Post only flag (for limit order only) + :type post_only: bool + :param hidden: (optional) Hidden order flag (for limit order only) + :type hidden: bool + :param iceberg: (optional) Iceberg order flag (for limit order only) + :type iceberg: bool + :param visible_size: (optional) The maximum visible size of an iceberg order (for limit orders only) + :type visible_size: string + :param trade_type: (optional) - deprecated - TRADE (spot) is supported only (default is TRADE) + :type trade_type: string + + .. code:: python + + order = client.create_order('ETH-USDT', Client.ORDER_LIMIT, Client.SIDE_BUY, size=20, price=2000) + order = client.create_order('ETH-USDT', Client.ORDER_MARKET, Client.SIDE_BUY, funds=20) + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "orderId": "672a249054d62a0007ae04b8", + "clientOid": "988a99edda5e496e95eb6e050c444994" + } + } + + :raises: KucoinResponseException, KucoinAPIException, MarketOrderException, LimitOrderException, KucoinRequestException + + """ + trade_type = trade_type or params.get('trade_type') or params.get('tradeType') + + if trade_type and trade_type != 'TRADE': + raise KucoinRequestException('trade_type is deprecated. Only TRADE (spot) is supported. For margin orders use create_margin_order()') + + if not client_oid: + client_oid = flat_uuid() + + data = self.get_common_data_for_order(symbol, type, side, size, price, funds, client_oid, stp, remark, + time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) + return self._post('orders', True, data=dict(data, **params)) + def create_market_order(self, symbol, side, size=None, funds=None, client_oid=None, remark=None, stp=None, **params): - """Create a market order + """Create a spot market order One of size or funds must be set - https://docs.kucoin.com/#place-a-new-order + https://www.kucoin.com/docs/rest/spot-trading/orders/place-order :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string @@ -2520,8 +2591,6 @@ def create_market_order(self, symbol, side, size=None, funds=None, client_oid=No :type remark: string :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) :type stp: string - :param trade_type: (optional) The type of trading : TRADE(Spot Trade), MARGIN_TRADE (Margin Trade). Default is TRADE - :type trade_type: string .. code:: python @@ -2539,32 +2608,73 @@ def create_market_order(self, symbol, side, size=None, funds=None, client_oid=No """ - if not size and not funds: - raise MarketOrderException('Need size or fund parameter') + return self.create_order(symbol, self.ORDER_MARKET, side, size=size, funds=funds, client_oid=client_oid, + remark=remark, stp=stp, **params) - if size and funds: - raise MarketOrderException('Need size or fund parameter not both') + def create_limit_order(self, symbol, side, price, size, client_oid=None, remark=None, + time_in_force=None, stop=None, stop_price=None, stp=None, trade_type=None, + cancel_after=None, post_only=None, + hidden=None, iceberg=None, visible_size=None, **params): + """Create a spot limit order - data = { - 'side': side, - 'symbol': symbol, - 'type': self.ORDER_MARKET - } + https://docs.kucoin.com/#place-a-new-order - if size: - data['size'] = size - if funds: - data['funds'] = funds - if client_oid: - data['clientOid'] = client_oid - else: - data['clientOid'] = flat_uuid() - if remark: - data['remark'] = remark - if stp: - data['stp'] = stp + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param side: buy or sell + :type side: string + :param price: Name of coin + :type price: string + :param size: Amount of base currency to buy or sell + :type size: string + :param client_oid: (optional) Unique order_id default flat_uuid() + :type client_oid: string + :param remark: (optional) remark for the order, max 100 utf8 characters + :type remark: string + :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) + :type stp: string + :param trade_type: (optional) - deprecated - TRADE (spot) is supported only (default is TRADE) + :type trade_type: string + :param time_in_force: (optional) GTC, GTT, IOC, or FOK (default is GTC) + :type time_in_force: string + :param stop: (deprecated) not supported + :param stop_price: (deprecated) not supported + :param cancel_after: (optional) number of seconds to cancel the order if not filled + required time_in_force to be GTT + :type cancel_after: string + :param post_only: (optional) indicates that the order should only make liquidity. If any part of + the order results in taking liquidity, the order will be rejected and no part of it will execute. + :type post_only: bool + :param hidden: (optional) Orders not displayed in order book + :type hidden: bool + :param iceberg: (optional) Only visible portion of the order is displayed in the order book + :type iceberg: bool + :param visible_size: (optional) The maximum visible size of an iceberg order + :type visible_size: string - return self._post('orders', True, data=dict(data, **params)) + .. code:: python + + order = client.create_limit_order('KCS-BTC', Client.SIDE_BUY, '0.01', '1000') + + :returns: ApiResponse + + .. code:: python + + { + "orderOid": "596186ad07015679730ffa02" + } + + :raises: KucoinResponseException, KucoinAPIException, LimitOrderException + + """ + + if stop or stop_price: + raise KucoinRequestException('stop and stop_price in create_limit_order are deprecated. To create a stop order please use create_stop_order()') + + return self.create_order(symbol, self.ORDER_LIMIT, side, size=size, price=price, client_oid=client_oid, + remark=remark, stp=stp, time_in_force=time_in_force, cancel_after=cancel_after, + post_only=post_only, hidden=hidden, iceberg=iceberg, visible_size=visible_size, + trade_type=trade_type, **params) def hf_create_order (self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, remark=None, time_in_force=None, cancel_after=None, post_only=None, @@ -2589,8 +2699,6 @@ def hf_create_order (self, symbol, type, side, size=None, price=None, funds=None :type client_oid: string :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) :type stp: string - :param tags: (optional) order tag, length cannot exceed 20 characters (ASCII) - :type tags: string :param remark: (optional) remark for the order, max 100 utf8 characters :type remark: string :param time_in_force: (optional) GTC, GTT, IOC, or FOK - default is GTC (for limit order only) @@ -2605,6 +2713,8 @@ def hf_create_order (self, symbol, type, side, size=None, price=None, funds=None :type iceberg: bool :param visible_size: (optional) The maximum visible size of an iceberg order (for limit orders only) :type visible_size: string + :param tags: (optional) order tag, length cannot exceed 20 characters (ASCII) + :type tags: string .. code:: python @@ -2637,12 +2747,12 @@ def hf_create_order (self, symbol, type, side, size=None, price=None, funds=None def hf_create_market_order(self, symbol, side, size=None, funds=None, client_oid=None, - stp=None, tags=None, remark=None, **params): + stp=None, remark=None, tags=None, **params): """Create a hf spot market order One of size or funds must be set - https://docs.kucoin.com/#place-hf-order + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/place-hf-order :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string @@ -2656,10 +2766,10 @@ def hf_create_market_order(self, symbol, side, size=None, funds=None, client_oid :type client_oid: string :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) :type stp: string - :param tags: (optional) order tag, length cannot exceed 20 characters (ASCII) - :type tags: string :param remark: (optional) remark for the order, max 100 utf8 characters :type remark: string + :param tags: (optional) order tag, length cannot exceed 20 characters (ASCII) + :type tags: string .. code:: python @@ -2684,121 +2794,12 @@ def hf_create_market_order(self, symbol, side, size=None, funds=None, client_oid return self.hf_create_order(symbol, self.ORDER_MARKET, side, size, funds=funds, client_oid=client_oid, stp=stp, remark=remark, tags=tags, **params) - def create_limit_order(self, symbol, side, price, size, client_oid=None, remark=None, - time_in_force=None, stop=None, stop_price=None, stp=None, trade_type=None, - cancel_after=None, post_only=None, - hidden=None, iceberg=None, visible_size=None): - """Create a limit order - - https://docs.kucoin.com/#place-a-new-order - - :param symbol: Name of symbol e.g. KCS-BTC - :type symbol: string - :param side: buy or sell - :type side: string - :param price: Name of coin - :type price: string - :param size: Amount of base currency to buy or sell - :type size: string - :param client_oid: (optional) Unique order_id default flat_uuid() - :type client_oid: string - :param remark: (optional) remark for the order, max 100 utf8 characters - :type remark: string - :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) - :type stp: string - :param trade_type: (optional) The type of trading : TRADE(Spot Trade), MARGIN_TRADE (Margin Trade). Default is TRADE - :type trade_type: string - :param time_in_force: (optional) GTC, GTT, IOC, or FOK (default is GTC) - :type time_in_force: string - :param stop: (optional) stop type loss or entry - requires stop_price - :type stop: string - :param stop_price: (optional) trigger price for stop order - :type stop_price: string - :param cancel_after: (optional) number of seconds to cancel the order if not filled - required time_in_force to be GTT - :type cancel_after: string - :param post_only: (optional) indicates that the order should only make liquidity. If any part of - the order results in taking liquidity, the order will be rejected and no part of it will execute. - :type post_only: bool - :param hidden: (optional) Orders not displayed in order book - :type hidden: bool - :param iceberg: (optional) Only visible portion of the order is displayed in the order book - :type iceberg: bool - :param visible_size: (optional) The maximum visible size of an iceberg order - :type visible_size: string - - .. code:: python - - order = client.create_limit_order('KCS-BTC', Client.SIDE_BUY, '0.01', '1000') - - :returns: ApiResponse - - .. code:: python - - { - "orderOid": "596186ad07015679730ffa02" - } - - :raises: KucoinResponseException, KucoinAPIException, LimitOrderException - - """ - - if stop and not stop_price: - raise LimitOrderException('Stop order needs stop_price') - - if stop_price and not stop: - raise LimitOrderException('Stop order type required with stop_price') - - if cancel_after and time_in_force != self.TIMEINFORCE_GOOD_TILL_TIME: - raise LimitOrderException('Cancel after only works with time_in_force = "GTT"') - - if hidden and iceberg: - raise LimitOrderException('Order can be either "hidden" or "iceberg"') - - if iceberg and not visible_size: - raise LimitOrderException('Iceberg order requires visible_size') - - data = { - 'symbol': symbol, - 'side': side, - 'type': self.ORDER_LIMIT, - 'price': price, - 'size': size - } - - if client_oid: - data['clientOid'] = client_oid - else: - data['clientOid'] = flat_uuid() - if remark: - data['remark'] = remark - if stp: - data['stp'] = stp - if trade_type: - data['tradeType'] = trade_type - if time_in_force: - data['timeInForce'] = time_in_force - if cancel_after: - data['cancelAfter'] = cancel_after - if post_only: - data['postOnly'] = post_only - if stop: - data['stop'] = stop - data['stopPrice'] = stop_price - if hidden: - data['hidden'] = hidden - if iceberg: - data['iceberg'] = iceberg - data['visible_size'] = visible_size - - return self._post('orders', True, data=data) - def hf_create_limit_order(self, symbol, side, price, size, client_oid=None, stp=None, remark=None, time_in_force=None, cancel_after=None, post_only=None, hidden=None, iceberg=None, visible_size=None, tags=None, **params): """Create a hf spot limit order - https://docs.kucoin.com/#place-hf-order + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/place-hf-order :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string @@ -2812,8 +2813,6 @@ def hf_create_limit_order(self, symbol, side, price, size, client_oid=None, stp= :type client_oid: string :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) :type stp: string - :param tags: (optional) order tag, length cannot exceed 20 characters (ASCII) - :type tags: string :param remark: (optional) remark for the order, max 100 utf8 characters :type remark: string :param time_in_force: (optional) GTC, GTT, IOC, or FOK (default is GTC) @@ -2830,6 +2829,8 @@ def hf_create_limit_order(self, symbol, side, price, size, client_oid=None, stp= :type iceberg: bool :param visible_size: (optional) The maximum visible size of an iceberg order :type visible_size: bool + :param tags: (optional) order tag, length cannot exceed 20 characters (ASCII) + :type tags: string .. code:: python From cc7c1098eb47e274b45aa21c3fbf7c3662f9b07e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Thu, 7 Nov 2024 19:58:58 +0300 Subject: [PATCH 32/60] create_test_order added --- kucoin/client.py | 71 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 67 insertions(+), 4 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 630b258..888611b 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -2499,7 +2499,7 @@ def get_common_data_for_order(self, symbol, type, side, size=None, price=None, f def create_order(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, remark=None, time_in_force=None, cancel_after=None, post_only=None, - hidden=None, iceberg=None, visible_size=None, trade_type=None, **params): + hidden=None, iceberg=None, visible_size=None, **params): """Create a spot order https://www.kucoin.com/docs/rest/spot-trading/orders/place-order @@ -2534,8 +2534,6 @@ def create_order(self, symbol, type, side, size=None, price=None, funds=None, cl :type iceberg: bool :param visible_size: (optional) The maximum visible size of an iceberg order (for limit orders only) :type visible_size: string - :param trade_type: (optional) - deprecated - TRADE (spot) is supported only (default is TRADE) - :type trade_type: string .. code:: python @@ -2557,8 +2555,8 @@ def create_order(self, symbol, type, side, size=None, price=None, funds=None, cl :raises: KucoinResponseException, KucoinAPIException, MarketOrderException, LimitOrderException, KucoinRequestException """ - trade_type = trade_type or params.get('trade_type') or params.get('tradeType') + trade_type = params.get('trade_type') or params.get('tradeType') if trade_type and trade_type != 'TRADE': raise KucoinRequestException('trade_type is deprecated. Only TRADE (spot) is supported. For margin orders use create_margin_order()') @@ -2676,6 +2674,71 @@ def create_limit_order(self, symbol, side, price, size, client_oid=None, remark= post_only=post_only, hidden=hidden, iceberg=iceberg, visible_size=visible_size, trade_type=trade_type, **params) + def create_test_order(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, + remark=None, time_in_force=None, cancel_after=None, post_only=None, + hidden=None, iceberg=None, visible_size=None, **params): + """Create a test spot order + + https://www.kucoin.com/docs/rest/spot-trading/orders/place-order-test + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param type: order type (limit or market) + :type type: string + :param side: buy or sell + :type side: string + :param size: (optional) Desired amount in base currency (required for limit order) + :type size: string + :param price: (optional) Price (required for limit order) + :type price: string + :param funds: (optional) Desired amount of quote currency to use (for market order only) + :type funds: string + :param client_oid: (optional) Unique order id (default flat_uuid()) + :type client_oid: string + :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) + :type stp: string + :param remark: (optional) remark for the order, max 100 utf8 characters + :type remark: string + :param time_in_force: (optional) GTC, GTT, IOC, or FOK - default is GTC (for limit order only) + :type time_in_force: string + :param cancel_after: (optional) time in ms to cancel after (for limit order only) + :type cancel_after: string + :param post_only: (optional) Post only flag (for limit order only) + :type post_only: bool + :param hidden: (optional) Hidden order flag (for limit order only) + :type hidden: bool + :param iceberg: (optional) Iceberg order flag (for limit order only) + :type iceberg: bool + :param visible_size: (optional) The maximum visible size of an iceberg order (for limit orders only) + :type visible_size: string + + .. code:: python + + order = client.create_test_order('ETH-USDT', Client.ORDER_LIMIT, Client.SIDE_BUY, size=20, price=2000) + order = client.create_test_order('ETH-USDT', Client.ORDER_MARKET, Client.SIDE_BUY, funds=20) + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "orderId": "672cf15bb2cdb8000708765c" + } + } + + :raises: KucoinResponseException, KucoinAPIException, MarketOrderException, LimitOrderException, KucoinRequestException + + """ + + if not client_oid: + client_oid = flat_uuid() + + data = self.get_common_data_for_order(symbol, type, side, size, price, funds, client_oid, stp, remark, + time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) + return self._post('orders/test', True, data=dict(data, **params)) + def hf_create_order (self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, remark=None, time_in_force=None, cancel_after=None, post_only=None, hidden=None, iceberg=None, visible_size=None, tags=None, **params): From 778faeea374b5272fb38588cf7aaf11d40c3182a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Thu, 7 Nov 2024 20:31:18 +0300 Subject: [PATCH 33/60] create_orders added --- kucoin/client.py | 57 ++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 53 insertions(+), 4 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 888611b..0327fd1 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -2421,7 +2421,7 @@ def futures_get_trading_pair_fee(self, symbol, **params): # Order Endpoints - def get_common_data_for_order(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, + def get_common_order_data(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, remark=None, time_in_force=None, cancel_after=None, post_only=None, hidden=None, iceberg=None, visible_size=None): """Internal helper for creating a common data for order""" @@ -2563,7 +2563,7 @@ def create_order(self, symbol, type, side, size=None, price=None, funds=None, cl if not client_oid: client_oid = flat_uuid() - data = self.get_common_data_for_order(symbol, type, side, size, price, funds, client_oid, stp, remark, + data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) return self._post('orders', True, data=dict(data, **params)) @@ -2735,10 +2735,59 @@ def create_test_order(self, symbol, type, side, size=None, price=None, funds=Non if not client_oid: client_oid = flat_uuid() - data = self.get_common_data_for_order(symbol, type, side, size, price, funds, client_oid, stp, remark, + data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) return self._post('orders/test', True, data=dict(data, **params)) + def create_orders(self, symbol, order_list, **params): + """Create multiple spot limit orders + + Maximum of 5 orders can be created at once + Only limit orders are supported + + https://www.kucoin.com/docs/rest/spot-trading/orders/place-multiple-orders + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param order_list: List of orders to create + :type order_list: list of dict + every order should have keys described inside of get_order_data_for_create_orders method + + .. code:: python + + order_list = [ + { + "side": "buy", + "price": "3000", + "size": "0.1", + "client_oid": "my_order_id_1" + }, + { + "side": "sell", + "type": "limit", + "price": "3500", + "size": "0.1", + } + ] + orders = client.create_orders('ETH-USDT', order_list) + + :returns: ApiResponse + + .. code:: python + + + + :raises: KucoinResponseException, KucoinAPIException, KucoinRequestException, LimitOrderException + + """ + + data = { + 'symbol': symbol, + 'orderList': order_list + } + + return self._post('orders/multi', True, data=dict(data, **params)) + def hf_create_order (self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, remark=None, time_in_force=None, cancel_after=None, post_only=None, hidden=None, iceberg=None, visible_size=None, tags=None, **params): @@ -2800,7 +2849,7 @@ def hf_create_order (self, symbol, type, side, size=None, price=None, funds=None """ - data = self.get_common_data_for_order(symbol, type, side, size, price, funds, client_oid, stp, remark, + data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) if tags: From bdfff37306fc9c9dbc6511008f4a48b389fadad8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Thu, 7 Nov 2024 21:07:10 +0300 Subject: [PATCH 34/60] create_orders updated --- kucoin/client.py | 42 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 0327fd1..8e78633 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -2751,7 +2751,21 @@ def create_orders(self, symbol, order_list, **params): :type symbol: string :param order_list: List of orders to create :type order_list: list of dict - every order should have keys described inside of get_order_data_for_create_orders method + every order should have the following keys: + - side: buy or sell + - price: Price + - size: Amount in base currency + - client_oid: (optional) Unique order id + - remark: (optional) remark for the order, max 100 utf8 characters + - stp: (optional) self trade protection CN, CO, CB or DC (default is None) + - time_in_force: (optional) GTC, GTT, IOC, or FOK - default is GTC + - cancel_after: (optional) time in ms to cancel after + - post_only: (optional) Post only flag + - hidden: (optional) Hidden order flag + - iceberg: (optional) Iceberg order flag + - visible_size: (optional) The maximum visible size of an iceberg order + - stop: (optional) loss or entry + - stop_price: (optional) stop price - required for stop orders .. code:: python @@ -2781,9 +2795,33 @@ def create_orders(self, symbol, order_list, **params): """ + orders = [] + + for order in order_list: + if 'type' in order and order['type'] != self.ORDER_LIMIT: + raise KucoinRequestException('Only limit orders are supported by create_orders') + order_data = self.get_common_order_data(symbol, self.ORDER_LIMIT, order['side'], order['size'], order['price'], + client_oid=order.get('client_oid'), remark=order.get('remark'), + stp=order.get('stp'), time_in_force=order.get('time_in_force'), + cancel_after=order.get('cancel_after'), post_only=order.get('post_only'), + hidden=order.get('hidden'), iceberg=order.get('iceberg'), + visible_size=order.get('visible_size')) + if 'client_oid' not in order_data: + order_data['clientOid'] = flat_uuid() + if 'stop' in order: + if not 'stop_price' in order: + raise LimitOrderException('Stop order needs stop_price') + if order['stop'] not in ['loss', 'entry']: + raise LimitOrderException('Stop order type must be loss or entry') + order_data['stop'] = order['stop'] + order_data['stopPrice'] = order['stop_price'] + elif 'stop_price' in order: + raise LimitOrderException('Stop price is only valid with stop order. Provide stop parameter (loss or entry)') + orders.append(order_data) + data = { 'symbol': symbol, - 'orderList': order_list + 'orderList': orders } return self._post('orders/multi', True, data=dict(data, **params)) From 3d867242409386cb02a9122bc784ad4fc4a05e0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Fri, 8 Nov 2024 16:37:40 +0300 Subject: [PATCH 35/60] delete methods updated --- kucoin/client.py | 94 ++++++++++++++++++++++++++++++++++-------------- 1 file changed, 67 insertions(+), 27 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 8e78633..8c140cb 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -44,11 +44,11 @@ class Client(object): TIMEINFORCE_IMMEDIATE_OR_CANCEL = 'IOC' TIMEINFORCE_FILL_OR_KILL = 'FOK' - # SPOT_KC_PARTNER = 'ccxt' # todo handle with standard python-kucoin signature - # SPOT_KC_KEY = '9e58cc35-5b5e-4133-92ec-166e3f077cb8' + SPOT_KC_PARTNER = 'ccxt' # todo handle with standard python-kucoin signature + SPOT_KC_KEY = '9e58cc35-5b5e-4133-92ec-166e3f077cb8' - SPOT_KC_PARTNER = 'python-kucoinspot' - SPOT_KC_KEY = '922783d1-067e-4a31-bb42-4d1589624e30' + # SPOT_KC_PARTNER = 'python-kucoinspot' + # SPOT_KC_KEY = '922783d1-067e-4a31-bb42-4d1589624e30' def __init__(self, api_key, api_secret, passphrase, sandbox=False, requests_params=None): """Kucoin API Client constructor @@ -123,7 +123,7 @@ def _generate_signature(self, nonce, method, path, data): data_json = "" endpoint = path - if method == "get": + if method == "get" or method == "delete": if data: query_string = self._get_params_for_sig(data) endpoint = "{}?{}".format(path, query_string) @@ -164,12 +164,12 @@ def _request(self, method, path, signed, api_version=None, **kwargs): kwargs['headers']['KC-API-PARTNER-VERIFY'] = 'true' kwargs['headers']['KC-API-PARTNER-SIGN'] = self._sign_partner() - if kwargs['data'] and method == 'get': - kwargs['params'] = kwargs['data'] - del kwargs['data'] - - if signed and method != 'get' and kwargs['data']: - kwargs['data'] = compact_json_dict(kwargs['data']) + if kwargs['data']: + if method == 'post': + kwargs['data'] = compact_json_dict(kwargs['data']) + else: + kwargs['params'] = kwargs['data'] + del kwargs['data'] response = getattr(self.session, method)(uri, **kwargs) return self._handle_response(response) @@ -2789,7 +2789,36 @@ def create_orders(self, symbol, order_list, **params): .. code:: python - + { + "code": "200000", + "data": { + "data": [ + { + "symbol": "ETH-USDT", + "type": "limit", + "side": "buy", + "price": "100", + "size": "0.01", + "funds": null, + "stp": "", + "stop": "loss", + "stopPrice": "90", + "timeInForce": "GTC", + "cancelAfter": 0, + "postOnly": false, + "hidden": false, + "iceberge": false, + "iceberg": false, + "visibleSize": null, + "channel": "API", + "id": "672e023a54d62a0007a60f73", + "status": "success", + "failMsg": null, + "clientOid": "test_create_orders" + } + ] + } + } :raises: KucoinResponseException, KucoinAPIException, KucoinRequestException, LimitOrderException @@ -2806,7 +2835,8 @@ def create_orders(self, symbol, order_list, **params): cancel_after=order.get('cancel_after'), post_only=order.get('post_only'), hidden=order.get('hidden'), iceberg=order.get('iceberg'), visible_size=order.get('visible_size')) - if 'client_oid' not in order_data: + del order_data['symbol'] + if 'clientOid' not in order_data: order_data['clientOid'] = flat_uuid() if 'stop' in order: if not 'stop_price' in order: @@ -3006,17 +3036,17 @@ def hf_create_limit_order(self, symbol, side, price, size, client_oid=None, stp= stp=stp, remark=remark, time_in_force=time_in_force, cancel_after=cancel_after, post_only=post_only, hidden=hidden, iceberg=iceberg, visible_size=visible_size, tags=tags, **params) - def cancel_order(self, order_id): - """Cancel an order + def cancel_order(self, order_id, **params): + """Cancel a spot order - https://docs.kucoin.com/#cancel-an-order + https://www.kucoin.com/docs/rest/spot-trading/orders/cancel-order-by-orderid :param order_id: Order id :type order_id: string .. code:: python - res = client.cancel_order('5bd6e9286d99522a52e458de) + res = client.cancel_order('5bd6e9286d99522a52e458de') :returns: ApiResponse @@ -3034,19 +3064,19 @@ def cancel_order(self, order_id): """ - return self._delete('orders/{}'.format(order_id), True) + return self._delete('orders/{}'.format(order_id), True, data=params) - def cancel_order_by_client_oid(self, client_oid): - """Cancel an order by the clientOid + def cancel_order_by_client_oid(self, client_oid, **params): + """Cancel a spot order by the clientOid - https://docs.kucoin.com/#cancel-single-order-by-clientoid + https://www.kucoin.com/docs/rest/spot-trading/orders/cancel-order-by-clientoid :param client_oid: ClientOid :type client_oid: string .. code:: python - res = client.cancel_order_by_client_oid('6d539dc614db3) + res = client.cancel_order_by_client_oid('6d539dc614db3') :returns: ApiResponse @@ -3063,7 +3093,7 @@ def cancel_order_by_client_oid(self, client_oid): """ - return self._delete('hf/orders/{}'.format(client_oid), True) + return self._delete('order/client-order/{}'.format(client_oid), True, data=params) def hf_cancel_order(self, order_id, symbol): """Cancel a hf order by the orderId @@ -3139,10 +3169,17 @@ def hf_cancel_order_by_client_oid(self, client_oid, symbol): return self._delete('hf/orders/client-order{}'.format(client_oid), True, data=data) - def cancel_all_orders(self, symbol=None): + def cancel_all_orders(self, symbol=None, trade_type=None, **params): """Cancel all orders - https://docs.kucoin.com/#cancel-all-orders + https://www.kucoin.com/docs/rest/spot-trading/orders/cancel-all-orders + + :param symbol: (optional) Name of symbol e.g. ETH-USDT + :type symbol: string + :param trade_type: (optional) The type of trading: + TRADE - spot trading, MARGIN_TRADE - cross margin trading, MARGIN_ISOLATED_TRADE - isolated margin trading + default is TRADE + :type trade_type: string .. code:: python @@ -3162,9 +3199,12 @@ def cancel_all_orders(self, symbol=None): """ data = {} - if symbol is not None: + if symbol: data['symbol'] = symbol - return self._delete('orders', True, data=data) + if trade_type: + data['tradeType'] = trade_type + + return self._delete('orders', True, data=dict(data, **params)) def hf_cancel_all_orders(self): """Cancel all orders From 9a303f96dd217fba41b707b2f903fb2f9c6d6ec9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Mon, 11 Nov 2024 17:05:09 +0300 Subject: [PATCH 36/60] get_orders updated --- kucoin/client.py | 162 ++++++++++++++++++++++++----------------------- 1 file changed, 84 insertions(+), 78 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 8c140cb..12ead85 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -3095,6 +3095,43 @@ def cancel_order_by_client_oid(self, client_oid, **params): return self._delete('order/client-order/{}'.format(client_oid), True, data=params) + def cancel_all_orders(self, symbol=None, trade_type=None, **params): + """Cancel all orders + + https://www.kucoin.com/docs/rest/spot-trading/orders/cancel-all-orders + + :param symbol: (optional) Name of symbol e.g. ETH-USDT + :type symbol: string + :param trade_type: (optional) The type of trading: + TRADE - spot trading, MARGIN_TRADE - cross margin trading, MARGIN_ISOLATED_TRADE - isolated margin trading + default is TRADE + :type trade_type: string + + .. code:: python + + res = client.cancel_all_orders() + + :returns: ApiResponse + + .. code:: python + + { + "cancelledOrderIds": [ + "5bd6e9286d99522a52e458de" + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + data = {} + if symbol: + data['symbol'] = symbol + if trade_type: + data['tradeType'] = trade_type + + return self._delete('orders', True, data=dict(data, **params)) + def hf_cancel_order(self, order_id, symbol): """Cancel a hf order by the orderId @@ -3169,43 +3206,6 @@ def hf_cancel_order_by_client_oid(self, client_oid, symbol): return self._delete('hf/orders/client-order{}'.format(client_oid), True, data=data) - def cancel_all_orders(self, symbol=None, trade_type=None, **params): - """Cancel all orders - - https://www.kucoin.com/docs/rest/spot-trading/orders/cancel-all-orders - - :param symbol: (optional) Name of symbol e.g. ETH-USDT - :type symbol: string - :param trade_type: (optional) The type of trading: - TRADE - spot trading, MARGIN_TRADE - cross margin trading, MARGIN_ISOLATED_TRADE - isolated margin trading - default is TRADE - :type trade_type: string - - .. code:: python - - res = client.cancel_all_orders() - - :returns: ApiResponse - - .. code:: python - - { - "cancelledOrderIds": [ - "5bd6e9286d99522a52e458de" - ] - } - - :raises: KucoinResponseException, KucoinAPIException - - """ - data = {} - if symbol: - data['symbol'] = symbol - if trade_type: - data['tradeType'] = trade_type - - return self._delete('orders', True, data=dict(data, **params)) - def hf_cancel_all_orders(self): """Cancel all orders @@ -3239,10 +3239,10 @@ def hf_cancel_all_orders(self): def get_orders(self, symbol=None, status=None, side=None, order_type=None, - start=None, end=None, page=None, limit=None, trade_type='TRADE'): + start=None, end=None, page=None, limit=None, trade_type=None, **params): """Get list of orders - https://docs.kucoin.com/#list-orders + https://www.kucoin.com/docs/rest/spot-trading/orders/get-order-list :param symbol: (optional) Name of symbol e.g. KCS-BTC :type symbol: string @@ -3252,7 +3252,9 @@ def get_orders(self, symbol=None, status=None, side=None, order_type=None, :type side: string :param order_type: (optional) limit, market, limit_stop or market_stop :type order_type: string - :param trade_type: The type of trading : TRADE(Spot Trading), MARGIN_TRADE (Margin Trading). + :param trade_type: (optional) The type of trading : + TRADE - spot trading, MARGIN_TRADE - cross margin trading, MARGIN_ISOLATED_TRADE - isolated margin trading + default is TRADE :type trade_type: string :param start: (optional) Start time as unix timestamp :type start: string @@ -3272,43 +3274,47 @@ def get_orders(self, symbol=None, status=None, side=None, order_type=None, .. code:: python { - "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, - "iceberge": false, - "visibleSize": "0", - "cancelAfter": 0, - "channel": "IOS", - "clientOid": null, - "remark": null, - "tags": null, - "isActive": false, - "cancelExist": false, - "createdAt": 1547026471000 - } - ] + "code": "200000", + "data": { + "currentPage": 1, + "pageSize": 50, + "totalNum": 1, + "totalPage": 1, + "items": [ + { + "id": "67320d92429d8b0007a962d0", + "symbol": "ETH-USDT", + "opType": "DEAL", + "type": "limit", + "side": "buy", + "price": "100", + "size": "0.01", + "funds": "0", + "dealFunds": "0", + "dealSize": "0", + "fee": "0", + "feeCurrency": "USDT", + "stp": null, + "stop": null, + "stopTriggered": false, + "stopPrice": "0", + "timeInForce": "GTC", + "postOnly": false, + "hidden": false, + "iceberg": false, + "visibleSize": "0", + "cancelAfter": 0, + "channel": "API", + "clientOid": null, + "remark": null, + "tags": "partner:ccxt", + "isActive": true, + "cancelExist": false, + "createdAt": 1731333522333, + "tradeType": "TRADE" + } + ] + } } :raises: KucoinResponseException, KucoinAPIException @@ -3336,7 +3342,7 @@ def get_orders(self, symbol=None, status=None, side=None, order_type=None, if trade_type: data['tradeType'] = trade_type - return self._get('orders', True, data=data) + return self._get('orders', True, data=dict(data, **params)) def get_historical_orders(self, symbol=None, side=None, start=None, end=None, page=None, limit=None): From 883d8bec088bd3ae59335a32e5391452267f5210 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Mon, 11 Nov 2024 17:26:19 +0300 Subject: [PATCH 37/60] get_recent_orders added --- kucoin/client.py | 56 ++++++++++++------------------------------------ 1 file changed, 14 insertions(+), 42 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 12ead85..724ca19 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -3346,18 +3346,17 @@ def get_orders(self, symbol=None, status=None, side=None, order_type=None, def get_historical_orders(self, symbol=None, side=None, start=None, end=None, page=None, limit=None): - """List of KuCoin V1 historical orders. + """Deprecated - https://docs.kucoin.com/#get-v1-historical-orders-list + """ + + raise KucoinAPIException('The interface has been deprecated. Please use get_orders') + + def get_recent_orders(self, page=None, limit=None, **params): + """Get up to 1000 last orders in the last 24 hours. + + https://www.kucoin.com/docs/rest/spot-trading/orders/get-recent-orders-list - :param symbol: (optional) Name of symbol e.g. KCS-BTC - :type symbol: string - :param side: (optional) buy or sell - :type side: string - :param start: (optional) Start time as unix timestamp - :type start: string - :param end: (optional) End time as unix timestamp - :type end: string :param page: (optional) Page to fetch :type page: int :param limit: (optional) Number of orders @@ -3365,50 +3364,23 @@ def get_historical_orders(self, symbol=None, side=None, .. code:: python - orders = client.get_historical_orders(symbol='KCS-BTC') + orders = client.get_recent_orders() :returns: ApiResponse - .. code:: python - - { - "currentPage": 1, - "pageSize": 50, - "totalNum": 1, - "totalPage": 1, - "items": [ - { - "symbol": "SNOV-ETH", - "dealPrice": "0.0000246", - "dealValue": "0.018942", - "amount": "770", - "fee": "0.00001137", - "side": "sell", - "createdAt": 1540080199 - } - ] - } + todo add the response example :raises: KucoinResponseException, KucoinAPIException """ data = {} - - if symbol: - data['symbol'] = symbol - if side: - data['side'] = side - if start: - data['startAt'] = start - if end: - data['endAt'] = end if page: - data['currentPage'] = page + data['page'] = page if limit: - data['pageSize'] = limit + data['limit'] = limit - return self._get('hist-orders', True, data=data) + return self._get('limit/orders', True, data=dict(data, **params)) def get_order(self, order_id): """Get order details From 4fd7d414c7467189de4b9046331ee352b339dafb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Mon, 11 Nov 2024 19:38:33 +0300 Subject: [PATCH 38/60] methods for create and delete hf orders added --- kucoin/client.py | 1184 ++++++++++++++++++++++++++++++++-------------- 1 file changed, 827 insertions(+), 357 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 724ca19..1fcf452 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -2750,7 +2750,7 @@ def create_orders(self, symbol, order_list, **params): :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string :param order_list: List of orders to create - :type order_list: list of dict + :type order_list: list of dicts every order should have the following keys: - side: buy or sell - price: Price @@ -2856,12 +2856,540 @@ def create_orders(self, symbol, order_list, **params): return self._post('orders/multi', True, data=dict(data, **params)) - def hf_create_order (self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, + def cancel_order(self, order_id, **params): + """Cancel a spot order + + https://www.kucoin.com/docs/rest/spot-trading/orders/cancel-order-by-orderid + + :param order_id: Order id + :type order_id: string + + .. code:: python + + res = client.cancel_order('5bd6e9286d99522a52e458de') + + :returns: ApiResponse + + .. code:: python + + { + "cancelledOrderIds": [ + "5bd6e9286d99522a52e458de" + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + KucoinAPIException If order_id is not found + + """ + + return self._delete('orders/{}'.format(order_id), True, data=params) + + def cancel_order_by_client_oid(self, client_oid, **params): + """Cancel a spot order by the clientOid + + https://www.kucoin.com/docs/rest/spot-trading/orders/cancel-order-by-clientoid + + :param client_oid: ClientOid + :type client_oid: string + + .. code:: python + + res = client.cancel_order_by_client_oid('6d539dc614db3') + + :returns: ApiResponse + + .. code:: python + + { + "cancelledOrderId": "5f311183c9b6d539dc614db3", + "clientOid": "6d539dc614db3" + } + + :raises: KucoinResponseException, KucoinAPIException + + KucoinAPIException If order_id is not found + + """ + + return self._delete('order/client-order/{}'.format(client_oid), True, data=params) + + def cancel_all_orders(self, symbol=None, trade_type=None, **params): + """Cancel all orders + + https://www.kucoin.com/docs/rest/spot-trading/orders/cancel-all-orders + + :param symbol: (optional) Name of symbol e.g. ETH-USDT + :type symbol: string + :param trade_type: (optional) The type of trading: + TRADE - spot trading, MARGIN_TRADE - cross margin trading, MARGIN_ISOLATED_TRADE - isolated margin trading + default is TRADE + :type trade_type: string + + .. code:: python + + res = client.cancel_all_orders() + + :returns: ApiResponse + + .. code:: python + + { + "cancelledOrderIds": [ + "5bd6e9286d99522a52e458de" + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + data = {} + if symbol: + data['symbol'] = symbol + if trade_type: + data['tradeType'] = trade_type + + return self._delete('orders', True, data=dict(data, **params)) + + def get_orders(self, symbol=None, status=None, side=None, order_type=None, + start=None, end=None, page=None, limit=None, trade_type=None, **params): + """Get list of orders + + https://www.kucoin.com/docs/rest/spot-trading/orders/get-order-list + + :param symbol: (optional) Name of symbol e.g. KCS-BTC + :type symbol: string + :param status: (optional) Specify status active or done (default done) + :type status: string + :param side: (optional) buy or sell + :type side: string + :param order_type: (optional) limit, market, limit_stop or market_stop + :type order_type: string + :param trade_type: (optional) The type of trading : + TRADE - spot trading, MARGIN_TRADE - cross margin trading, MARGIN_ISOLATED_TRADE - isolated margin trading + default is TRADE + :type trade_type: string + :param start: (optional) Start time as unix timestamp + :type start: string + :param end: (optional) End time as unix timestamp + :type end: string + :param page: (optional) Page to fetch + :type page: int + :param limit: (optional) Number of orders + :type limit: int + + .. code:: python + + orders = client.get_orders(symbol='KCS-BTC', status='active') + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "currentPage": 1, + "pageSize": 50, + "totalNum": 1, + "totalPage": 1, + "items": [ + { + "id": "67320d92429d8b0007a962d0", + "symbol": "ETH-USDT", + "opType": "DEAL", + "type": "limit", + "side": "buy", + "price": "100", + "size": "0.01", + "funds": "0", + "dealFunds": "0", + "dealSize": "0", + "fee": "0", + "feeCurrency": "USDT", + "stp": null, + "stop": null, + "stopTriggered": false, + "stopPrice": "0", + "timeInForce": "GTC", + "postOnly": false, + "hidden": false, + "iceberg": false, + "visibleSize": "0", + "cancelAfter": 0, + "channel": "API", + "clientOid": null, + "remark": null, + "tags": "partner:ccxt", + "isActive": true, + "cancelExist": false, + "createdAt": 1731333522333, + "tradeType": "TRADE" + } + ] + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + + if symbol: + data['symbol'] = symbol + if status: + data['status'] = status + if side: + data['side'] = side + if order_type: + data['type'] = order_type + if start: + data['startAt'] = start + if end: + data['endAt'] = end + if page: + data['currentPage'] = page + if limit: + data['pageSize'] = limit + if trade_type: + data['tradeType'] = trade_type + + return self._get('orders', True, data=dict(data, **params)) + + def get_historical_orders(self, symbol=None, side=None, + start=None, end=None, page=None, limit=None): + """Deprecated + + """ + + raise KucoinAPIException('The interface has been deprecated. Please use get_orders') + + def get_recent_orders(self, page=None, limit=None, **params): + """Get up to 1000 last orders in the last 24 hours. + + https://www.kucoin.com/docs/rest/spot-trading/orders/get-recent-orders-list + + :param page: (optional) Page to fetch + :type page: int + :param limit: (optional) Number of orders + :type limit: int + + .. code:: python + + orders = client.get_recent_orders() + + :returns: ApiResponse + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + if page: + data['page'] = page + if limit: + data['limit'] = limit + + return self._get('limit/orders', True, data=dict(data, **params)) + + def get_order(self, order_id, **params): + """Get order details + + https://www.kucoin.com/docs/rest/spot-trading/orders/get-order-details-by-orderid + + :param order_id: orderOid value + :type order_id: str + + .. code:: python + + order = client.get_order('5c35c02703aa673ceec2a168') + + :returns: ApiResponse + + .. code:: python + + { + "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, + "iceberge": false, + "visibleSize": "0", + "cancelAfter": 0, + "channel": "IOS", + "clientOid": null, + "remark": null, + "tags": null, + "isActive": false, + "cancelExist": false, + "createdAt": 1547026471000 + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + return self._get('orders/{}'.format(order_id), True, data=params) + + def get_order_by_client_oid(self, client_oid, **params): + """Get order details by clientOid + + https://www.kucoin.com/docs/rest/spot-trading/orders/get-order-details-by-clientoid + + :param client_oid: clientOid value + :type client_oid: str + + .. code:: python + + order = client.get_order_by_client_oid('6d539dc614db312') + + :returns: ApiResponse + + .. code:: python + + { + "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": "", + "stop": "", + "stopTriggered": false, + "stopPrice": "0", + "timeInForce": "GTC", + "postOnly": false, + "hidden": false, + "iceberg": false, + "visibleSize": "0", + "cancelAfter": 0, + "channel": "API", + "clientOid": "6d539dc614db312", + "remark": "", + "tags": "", + "isActive": true, + "cancelExist": false, + "createdAt": 1597051810000, + "tradeType": "TRADE" + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + return self._get('order/client-order/{}'.format(client_oid), True, data=params) + + def hf_create_order(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, + remark=None, time_in_force=None, cancel_after=None, post_only=None, + hidden=None, iceberg=None, visible_size=None, tags=None, **params): + """Create a hf spot order + + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/place-hf-order + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param type: order type (limit or market) + :type type: string + :param side: buy or sell + :type side: string + :param size: (optional) Desired amount in base currency (required for limit order) + :type size: string + :param price: (optional) Price (required for limit order) + :type price: string + :param funds: (optional) Desired amount of quote currency to use (for market order only) + :type funds: string + :param client_oid: (optional) Unique order id (default flat_uuid()) + :type client_oid: string + :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) + :type stp: string + :param remark: (optional) remark for the order, max 100 utf8 characters + :type remark: string + :param time_in_force: (optional) GTC, GTT, IOC, or FOK - default is GTC (for limit order only) + :type time_in_force: string + :param cancel_after: (optional) time in ms to cancel after (for limit order only) + :type cancel_after: string + :param post_only: (optional) Post only flag (for limit order only) + :type post_only: bool + :param hidden: (optional) Hidden order flag (for limit order only) + :type hidden: bool + :param iceberg: (optional) Iceberg order flag (for limit order only) + :type iceberg: bool + :param visible_size: (optional) The maximum visible size of an iceberg order (for limit orders only) + :type visible_size: string + :param tags: (optional) order tag, length cannot exceed 20 characters (ASCII) + :type tags: string + + .. code:: python + + order = client.hf_create_order('ETH-USDT', Client.ORDER_LIMIT, Client.SIDE_BUY, size=20, price=2000) + order = client.hf_create_order('ETH-USDT', Client.ORDER_MARKET, Client.SIDE_BUY, funds=20) + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "orderId": "672a249054d62a0007ae04b8", + "clientOid": "988a99edda5e496e95eb6e050c444994" + } + } + + :raises: KucoinResponseException, KucoinAPIException, MarketOrderException, LimitOrderException, KucoinRequestException + + """ + + data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, + time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) + + if tags: + data['tags'] = tags + + return self._post('hf/orders', True, data=dict(data, **params)) + + def hf_create_market_order(self, symbol, side, size=None, funds=None, client_oid=None, + stp=None, remark=None, tags=None, **params): + """Create a hf spot market order + + One of size or funds must be set + + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/place-hf-order + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param side: buy or sell + :type side: string + :param size: (optional) Desired amount in base currency + :type size: string + :param funds: (optional) Desired amount of quote currency to use + :type funds: string + :param client_oid: (optional) Unique order id (default flat_uuid()) + :type client_oid: string + :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) + :type stp: string + :param remark: (optional) remark for the order, max 100 utf8 characters + :type remark: string + :param tags: (optional) order tag, length cannot exceed 20 characters (ASCII) + :type tags: string + + .. code:: python + + order = client.hf_create_market_order('ETH-USDT', Client.SIDE_BUY, size=20) + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "orderId": "5bd6e9286d99522a52e458de", + "clientOid": "11223344" + } + } + + :raises: KucoinResponseException, KucoinAPIException, MarketOrderException + + """ + + return self.hf_create_order(symbol, self.ORDER_MARKET, side, size, funds=funds, client_oid=client_oid, + stp=stp, remark=remark, tags=tags, **params) + + def hf_create_limit_order(self, symbol, side, price, size, client_oid=None, stp=None, + remark=None, time_in_force=None, cancel_after=None, post_only=None, + hidden=None, iceberg=None, visible_size=None, tags=None, **params): + """Create a hf spot limit order + + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/place-hf-order + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param side: buy or sell + :type side: string + :param price: Name of coin + :type price: string + :param size: Amount of base currency to buy or sell + :type size: string + :param client_oid: (optional) Unique order_id default flat_uuid() + :type client_oid: string + :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) + :type stp: string + :param remark: (optional) remark for the order, max 100 utf8 characters + :type remark: string + :param time_in_force: (optional) GTC, GTT, IOC, or FOK (default is GTC) + :type time_in_force: string + :param cancel_after: (optional) number of seconds to cancel the order if not filled + required time_in_force to be GTT + :type cancel_after: string + :param post_only: (optional) indicates that the order should only make liquidity. If any part of + the order results in taking liquidity, the order will be rejected and no part of it will execute. + :type post_only: bool + :param hidden: (optional) Orders not displayed in order book + :type hidden: bool + :param iceberg: (optional) Only visible portion of the order is displayed in the order book + :type iceberg: bool + :param visible_size: (optional) The maximum visible size of an iceberg order + :type visible_size: bool + :param tags: (optional) order tag, length cannot exceed 20 characters (ASCII) + :type tags: string + + .. code:: python + + order = client.hf_create_limit_order('KCS-BTC', Client.SIDE_BUY, '0.01', '1000') + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "orderId": "5bd6e9286d99522a52e458de", + "clientOid": "11223344" + } + } + + :raises: KucoinResponseException, KucoinAPIException, LimitOrderException + + """ + + return self.hf_create_order(symbol, self.ORDER_LIMIT, side, size, price=price, client_oid=client_oid, + stp=stp, remark=remark, time_in_force=time_in_force, cancel_after=cancel_after, + post_only=post_only, hidden=hidden, iceberg=iceberg, visible_size=visible_size, tags=tags, **params) + + def hf_create_test_order(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, remark=None, time_in_force=None, cancel_after=None, post_only=None, hidden=None, iceberg=None, visible_size=None, tags=None, **params): - """Create a hf spot order + """Create a hf test spot order - https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/place-hf-order + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/place-hf-order-test :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string @@ -2898,8 +3426,8 @@ def hf_create_order (self, symbol, type, side, size=None, price=None, funds=None .. code:: python - order = client.hf_create_order('ETH-USDT', Client.ORDER_LIMIT, Client.SIDE_BUY, size=20, price=2000) - order = client.hf_create_order('ETH-USDT', Client.ORDER_MARKET, Client.SIDE_BUY, funds=20) + order = client.hf_create_test_order('ETH-USDT', Client.ORDER_LIMIT, Client.SIDE_BUY, size=20, price=2000) + order = client.hf_create_test_order('ETH-USDT', Client.ORDER_MARKET, Client.SIDE_BUY, funds=20) :returns: ApiResponse @@ -2923,24 +3451,28 @@ def hf_create_order (self, symbol, type, side, size=None, price=None, funds=None if tags: data['tags'] = tags - return self._post('hf/orders', True, data=dict(data, **params)) - + return self._post('hf/orders/test', True, data=dict(data, **params)) - def hf_create_market_order(self, symbol, side, size=None, funds=None, client_oid=None, - stp=None, remark=None, tags=None, **params): - """Create a hf spot market order - - One of size or funds must be set + def sync_hf_create_order(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, + remark=None, time_in_force=None, cancel_after=None, post_only=None, + hidden=None, iceberg=None, visible_size=None, tags=None, **params): + """Create a hf spot order + The difference between this interface and hf_create_order is that this interface will + synchronously return the order information after the order matching is completed - https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/place-hf-order + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/sync-place-hf-order :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string + :param type: order type (limit or market) + :type type: string :param side: buy or sell :type side: string - :param size: (optional) Desired amount in base currency + :param size: (optional) Desired amount in base currency (required for limit order) :type size: string - :param funds: (optional) Desired amount of quote currency to use + :param price: (optional) Price (required for limit order) + :type price: string + :param funds: (optional) Desired amount of quote currency to use (for market order only) :type funds: string :param client_oid: (optional) Unique order id (default flat_uuid()) :type client_oid: string @@ -2948,12 +3480,25 @@ def hf_create_market_order(self, symbol, side, size=None, funds=None, client_oid :type stp: string :param remark: (optional) remark for the order, max 100 utf8 characters :type remark: string + :param time_in_force: (optional) GTC, GTT, IOC, or FOK - default is GTC (for limit order only) + :type time_in_force: string + :param cancel_after: (optional) time in ms to cancel after (for limit order only) + :type cancel_after: string + :param post_only: (optional) Post only flag (for limit order only) + :type post_only: bool + :param hidden: (optional) Hidden order flag (for limit order only) + :type hidden: bool + :param iceberg: (optional) Iceberg order flag (for limit order only) + :type iceberg: bool + :param visible_size: (optional) The maximum visible size of an iceberg order (for limit orders only) + :type visible_size: string :param tags: (optional) order tag, length cannot exceed 20 characters (ASCII) :type tags: string .. code:: python - order = client.hf_create_market_order('ETH-USDT', Client.SIDE_BUY, size=20) + order = client.sync_hf_create_order('ETH-USDT', Client.ORDER_LIMIT, Client.SIDE_BUY, size=20, price=2000) + order = client.sync_hf_create_order('ETH-USDT', Client.ORDER_MARKET, Client.SIDE_BUY, funds=20) :returns: ApiResponse @@ -2962,180 +3507,273 @@ def hf_create_market_order(self, symbol, side, size=None, funds=None, client_oid { "code": "200000", "data": { - "orderId": "5bd6e9286d99522a52e458de", - "clientOid": "11223344" + "orderId": "673219d13cda6500071f613d", + "orderTime": 1731336657616, + "originSize": "0", + "dealSize": "0.0003158", + "remainSize": "0", + "canceledSize": "0", + "originFunds": "1", + "dealFunds": "0.999709112", + "remainFunds": "0", + "canceledFunds": "0.000290888", + "status": "done", + "matchTime": 1731336657641 } } - :raises: KucoinResponseException, KucoinAPIException, MarketOrderException + :raises: KucoinResponseException, KucoinAPIException, MarketOrderException, LimitOrderException, KucoinRequestException """ - return self.hf_create_order(symbol, self.ORDER_MARKET, side, size, funds=funds, client_oid=client_oid, - stp=stp, remark=remark, tags=tags, **params) + data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, + time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) - def hf_create_limit_order(self, symbol, side, price, size, client_oid=None, stp=None, - remark=None, time_in_force=None, cancel_after=None, post_only=None, - hidden=None, iceberg=None, visible_size=None, tags=None, **params): - """Create a hf spot limit order + if tags: + data['tags'] = tags - https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/place-hf-order + return self._post('hf/orders/sync', True, data=dict(data, **params)) - :param symbol: Name of symbol e.g. KCS-BTC - :type symbol: string - :param side: buy or sell - :type side: string - :param price: Name of coin - :type price: string - :param size: Amount of base currency to buy or sell - :type size: string - :param client_oid: (optional) Unique order_id default flat_uuid() - :type client_oid: string - :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) - :type stp: string - :param remark: (optional) remark for the order, max 100 utf8 characters - :type remark: string - :param time_in_force: (optional) GTC, GTT, IOC, or FOK (default is GTC) - :type time_in_force: string - :param cancel_after: (optional) number of seconds to cancel the order if not filled - required time_in_force to be GTT - :type cancel_after: string - :param post_only: (optional) indicates that the order should only make liquidity. If any part of - the order results in taking liquidity, the order will be rejected and no part of it will execute. - :type post_only: bool - :param hidden: (optional) Orders not displayed in order book - :type hidden: bool - :param iceberg: (optional) Only visible portion of the order is displayed in the order book - :type iceberg: bool - :param visible_size: (optional) The maximum visible size of an iceberg order - :type visible_size: bool - :param tags: (optional) order tag, length cannot exceed 20 characters (ASCII) - :type tags: string + def hf_create_orders(self, order_list, **params): + """Create multiple hf spot orders + + Maximum of 5 orders can be created at once + + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/place-multiple-orders + + :param order_list: List of orders to create + :type order_list: list of dicts + every order should have the following keys: + - symbol: Name of symbol e.g. ETH-USDT + - type: order type (limit or market) + - side: buy or sell + - size: amount in base currency + - price: (optional) price (mandatory for limit order) + - client_oid: (optional) unique order id + - remark: (optional) remark for the order, max 100 utf8 characters + - stp: (optional) self trade protection CN, CO, CB or DC (default is None) + - time_in_force: (optional) GTC, GTT, IOC, or FOK - default is GTC + - cancel_after: (optional) time in ms to cancel after + - post_only: (optional) Post only flag + - hidden: (optional) Hidden order flag + - iceberg: (optional) Iceberg order flag + - visible_size: (optional) The maximum visible size of an iceberg order + - tags: (optional) order tag, length cannot exceed 20 characters (ASCII) .. code:: python - order = client.hf_create_limit_order('KCS-BTC', Client.SIDE_BUY, '0.01', '1000') + order_list = [ + { + "symbol": "ETH-USDT", + "side": "buy", + 'type': 'market', + "size": "0.1", + "client_oid": "my_order_id_1" + }, + { + "symbol": "ETH-USDT", + "side": "sell", + "type": "limit", + "price": "3500", + "size": "0.1", + } + ] + orders = client.hf_create_orders(order_list) :returns: ApiResponse .. code:: python - { - "code": "200000", - "data": { - "orderId": "5bd6e9286d99522a52e458de", - "clientOid": "11223344" - } - } + todo add the response example - :raises: KucoinResponseException, KucoinAPIException, LimitOrderException + :raises: KucoinResponseException, KucoinAPIException, KucoinRequestException, LimitOrderException """ - return self.hf_create_order(symbol, self.ORDER_LIMIT, side, size, price=price, client_oid=client_oid, - stp=stp, remark=remark, time_in_force=time_in_force, cancel_after=cancel_after, - post_only=post_only, hidden=hidden, iceberg=iceberg, visible_size=visible_size, tags=tags, **params) + orders = [] - def cancel_order(self, order_id, **params): - """Cancel a spot order + for order in order_list: + order_data = self.get_common_order_data(order.get('symbol'), order.get('type'), order.get('side'), + order.get('size'), order.get('price'), order.get('funds'), + order.get('client_oid'), order.get('stp'), order.get('remark'), + order.get('time_in_force'), order.get('cancel_after'), order.get('post_only'), + order.get('hidden'), order.get('iceberg'), order.get('visible_size')) + if 'tags' in order: + order_data['tags'] = order['tags'] + orders.append(order_data) - https://www.kucoin.com/docs/rest/spot-trading/orders/cancel-order-by-orderid + data = { + 'orderList': orders + } - :param order_id: Order id - :type order_id: string + return self._post('hf/orders/multi', True, data=dict(data, **params)) + + def sync_hf_create_orders(self, order_list, **params): + """Create multiple hf spot orders + + The difference between this interface and hf_create_orders is that this interface will + synchronously return the order information after the order matching is completed + Maximum of 20 orders can be created at once + + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/sync-place-multiple-hf-orders + + :param order_list: List of orders to create + :type order_list: list of dicts + every order should have the following keys: + - symbol: Name of symbol e.g. ETH-USDT + - type: order type (limit or market) + - side: buy or sell + - size: amount in base currency + - price: (optional) price (mandatory for limit order) + - client_oid: (optional) unique order id + - remark: (optional) remark for the order, max 100 utf8 characters + - stp: (optional) self trade protection CN, CO, CB or DC (default is None) + - time_in_force: (optional) GTC, GTT, IOC, or FOK - default is GTC + - cancel_after: (optional) time in ms to cancel after + - post_only: (optional) Post only flag + - hidden: (optional) Hidden order flag + - iceberg: (optional) Iceberg order flag + - visible_size: (optional) The maximum visible size of an iceberg order + - tags: (optional) order tag, length cannot exceed 20 characters (ASCII) .. code:: python - res = client.cancel_order('5bd6e9286d99522a52e458de') + order_list = [ + { + { + "symbol": "ETH-USDT", + "side": "buy", + 'type': 'market', + "size": "0.1", + "client_oid": "my_order_id_1" + }, + { + "symbol": "ETH-USDT", + "side": "sell", + "type": "limit", + "price": "3500", + "size": "0.1", + } + ] + orders = client.sync_hf_create_orders(order_list) :returns: ApiResponse .. code:: python - { - "cancelledOrderIds": [ - "5bd6e9286d99522a52e458de" - ] - } - - :raises: KucoinResponseException, KucoinAPIException + todo add the response example - KucoinAPIException If order_id is not found + :raises: KucoinResponseException, KucoinAPIException, KucoinRequestException, LimitOrderException """ - return self._delete('orders/{}'.format(order_id), True, data=params) + orders = [] - def cancel_order_by_client_oid(self, client_oid, **params): - """Cancel a spot order by the clientOid + for order in order_list: + order_data = self.get_common_order_data(order.get('symbol'), order.get('type'), order.get('side'), + order.get('size'), order.get('price'), order.get('funds'), + order.get('client_oid'), order.get('stp'), order.get('remark'), + order.get('time_in_force'), order.get('cancel_after'), order.get('post_only'), + order.get('hidden'), order.get('iceberg'), order.get('visible_size')) + if 'tags' in order: + order_data['tags'] = order['tags'] + orders.append(order_data) - https://www.kucoin.com/docs/rest/spot-trading/orders/cancel-order-by-clientoid + data = { + 'orderList': orders + } + + return self._post('hf/orders/multi/sync', True, data=dict(data, **params)) + + def hf_modify_order(self, symbol, order_id=None, client_oid=None, new_size=None, new_price=None, **params): + """Modify an existing hf order + + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/modify-hf-order + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param order_id: OrderId + :type order_id: string :param client_oid: ClientOid :type client_oid: string + :param new_size: (optional) Desired amount in base currency + :type new_size: string + :param new_price: (optional) Price + :type new_price: string .. code:: python - res = client.cancel_order_by_client_oid('6d539dc614db3') + order = client.hf_modify_order('ETH-USDT', order_id='5c35c02703aa673ceec2a168', new_size='0.2') :returns: ApiResponse .. code:: python - { - "cancelledOrderId": "5f311183c9b6d539dc614db3", - "clientOid": "6d539dc614db3" - } + todo add the response example :raises: KucoinResponseException, KucoinAPIException - KucoinAPIException If order_id is not found - """ - return self._delete('order/client-order/{}'.format(client_oid), True, data=params) + data = { + 'symbol': symbol + } - def cancel_all_orders(self, symbol=None, trade_type=None, **params): - """Cancel all orders + if not order_id and not client_oid: + raise KucoinAPIException('Either order_id or client_oid is required') + if order_id and client_oid: + raise KucoinAPIException('Either order_id or client_oid is required, not both') - https://www.kucoin.com/docs/rest/spot-trading/orders/cancel-all-orders + if order_id: + data['orderId'] = order_id + if client_oid: + data['clientOid'] = client_oid + if new_size: + data['newSize'] = new_size + if new_price: + data['newPrice'] = new_price - :param symbol: (optional) Name of symbol e.g. ETH-USDT + return self._post('hf/orders/alter', True, data=dict(data, **params)) + + def hf_cancel_order(self, order_id, symbol, **params): + """Cancel an hf order by the orderId + + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/cancel-hf-order-by-orderid + + :param order_id: OrderId + :type order_id: string + :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string - :param trade_type: (optional) The type of trading: - TRADE - spot trading, MARGIN_TRADE - cross margin trading, MARGIN_ISOLATED_TRADE - isolated margin trading - default is TRADE - :type trade_type: string .. code:: python - res = client.cancel_all_orders() + res = client.hf_cancel_order_by_order_id('5bd6e9286d99522a52e458de', 'KCS-BTC') :returns: ApiResponse .. code:: python - { - "cancelledOrderIds": [ - "5bd6e9286d99522a52e458de" - ] - } + todo add the response example :raises: KucoinResponseException, KucoinAPIException + KucoinAPIException If order_id is not found + """ - data = {} - if symbol: - data['symbol'] = symbol - if trade_type: - data['tradeType'] = trade_type - return self._delete('orders', True, data=dict(data, **params)) + data = { + 'symbol': symbol + } + + return self._delete('hf/orders/{}'.format(order_id), True, data=dict(data, **params)) + + def sync_hf_cancel_order(self, order_id, symbol, **params): + """Cancel an hf order by the orderId + The difference between this interface and hf_cancel_order is that this interface will + synchronously return the order information after the order canceling is completed. - def hf_cancel_order(self, order_id, symbol): - """Cancel a hf order by the orderId + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/sync-cancel-hf-order-by-orderid - https://docs.kucoin.com/#cancel-hf-order-by-orderid :param order_id: OrderId :type order_id: string @@ -3144,18 +3782,13 @@ def hf_cancel_order(self, order_id, symbol): .. code:: python - res = client.hf_cancel_order_by_order_id('5bd6e9286d99522a52e458de', 'KCS-BTC') + res = client.sync_hf_cancel_order('5bd6e9286d99522a52e458de', 'KCS-BTC') :returns: ApiResponse .. code:: python - { - "code": "200000", - "data": { - "orderId": "630625dbd9180300014c8d52" - } - } + todo add the response example :raises: KucoinResponseException, KucoinAPIException @@ -3167,12 +3800,12 @@ def hf_cancel_order(self, order_id, symbol): 'symbol': symbol } - return self._delete('hf/orders/{}'.format(order_id), True, data=data) + return self._delete('hf/orders/sync/{}'.format(order_id), True, data=dict(data, **params)) - def hf_cancel_order_by_client_oid(self, client_oid, symbol): + def hf_cancel_order_by_client_oid(self, client_oid, symbol, **params): """Cancel a hf order by the clientOid - https://docs.kucoin.com/#cancel-hf-order-by-clientoid + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/cancel-hf-order-by-clientoid :param client_oid: ClientOid :type client_oid: string @@ -3187,12 +3820,7 @@ def hf_cancel_order_by_client_oid(self, client_oid, symbol): .. code:: python - { - "code": "200000", - "data": { - "clientOid": "6d539dc614db3" - } - } + todo add the response example :raises: KucoinResponseException, KucoinAPIException @@ -3204,237 +3832,134 @@ def hf_cancel_order_by_client_oid(self, client_oid, symbol): 'symbol': symbol } - return self._delete('hf/orders/client-order{}'.format(client_oid), True, data=data) + return self._delete('hf/orders/client-order{}'.format(client_oid), True, data=dict(data, **params)) - def hf_cancel_all_orders(self): - """Cancel all orders + def sync_hf_cancel_order_by_client_oid(self, client_oid, symbol, **params): + """Cancel a hf order by the clientOid + The difference between this interface and hf_cancel_order is that this interface will + synchronously return the order information after the order canceling is completed. + + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/sync-cancel-hf-order-by-orderid - https://docs.kucoin.com/#cancel-all-hf-orders + :param client_oid: ClientOid + :type client_oid: string + :param symbol: Name of symbol e.g. ETH-USDT + :type symbol: string .. code:: python - res = client.hf_cancel_all_orders() + res = client.sync_hf_cancel_order_by_client_oid('6d539dc614db3', 'ETH-USDT') :returns: ApiResponse .. code:: python - { - "succeedSymbols": [ - "BTC-USDT", - "ETH-USDT" - ], - "failedSymbols": [ - { - "symbol": "BTC-USDT", - "error": "can't cancel, system timeout" - } - ], - } + todo add the response example :raises: KucoinResponseException, KucoinAPIException + KucoinAPIException If order_id is not found + """ - return self._delete('hf/orders/cancelAll', True) + data = { + 'symbol': symbol + } + + return self._delete('hf/orders/sync/client-order/{}'.format(client_oid), True, data=dict(data, **params)) - def get_orders(self, symbol=None, status=None, side=None, order_type=None, - start=None, end=None, page=None, limit=None, trade_type=None, **params): - """Get list of orders + def hf_cancel_specified_quantity_of_order(self, order_id, symbol, cancel_size, **params): + """Cancel a specified quantity of an hf order by the orderId - https://www.kucoin.com/docs/rest/spot-trading/orders/get-order-list + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/cancel-specified-number-hf-orders-by-orderid - :param symbol: (optional) Name of symbol e.g. KCS-BTC + :param order_id: OrderId + :type order_id: string + :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string - :param status: (optional) Specify status active or done (default done) - :type status: string - :param side: (optional) buy or sell - :type side: string - :param order_type: (optional) limit, market, limit_stop or market_stop - :type order_type: string - :param trade_type: (optional) The type of trading : - TRADE - spot trading, MARGIN_TRADE - cross margin trading, MARGIN_ISOLATED_TRADE - isolated margin trading - default is TRADE - :type trade_type: string - :param start: (optional) Start time as unix timestamp - :type start: string - :param end: (optional) End time as unix timestamp - :type end: string - :param page: (optional) Page to fetch - :type page: int - :param limit: (optional) Number of orders - :type limit: int + :param cancel_size: The quantity to cancel + :type cancel_size: string .. code:: python - orders = client.get_orders(symbol='KCS-BTC', status='active') + res = client.hf_cancel_specified_quantity_of_order('5bd6e9286d99522a52e458de', 'ETH-USDT, '0.1') :returns: ApiResponse .. code:: python - { - "code": "200000", - "data": { - "currentPage": 1, - "pageSize": 50, - "totalNum": 1, - "totalPage": 1, - "items": [ - { - "id": "67320d92429d8b0007a962d0", - "symbol": "ETH-USDT", - "opType": "DEAL", - "type": "limit", - "side": "buy", - "price": "100", - "size": "0.01", - "funds": "0", - "dealFunds": "0", - "dealSize": "0", - "fee": "0", - "feeCurrency": "USDT", - "stp": null, - "stop": null, - "stopTriggered": false, - "stopPrice": "0", - "timeInForce": "GTC", - "postOnly": false, - "hidden": false, - "iceberg": false, - "visibleSize": "0", - "cancelAfter": 0, - "channel": "API", - "clientOid": null, - "remark": null, - "tags": "partner:ccxt", - "isActive": true, - "cancelExist": false, - "createdAt": 1731333522333, - "tradeType": "TRADE" - } - ] - } - } + todo add the response example :raises: KucoinResponseException, KucoinAPIException - """ - - data = {} - - if symbol: - data['symbol'] = symbol - if status: - data['status'] = status - if side: - data['side'] = side - if order_type: - data['type'] = order_type - if start: - data['startAt'] = start - if end: - data['endAt'] = end - if page: - data['currentPage'] = page - if limit: - data['pageSize'] = limit - if trade_type: - data['tradeType'] = trade_type - - return self._get('orders', True, data=dict(data, **params)) - - def get_historical_orders(self, symbol=None, side=None, - start=None, end=None, page=None, limit=None): - """Deprecated + KucoinAPIException """ - raise KucoinAPIException('The interface has been deprecated. Please use get_orders') + data = { + 'symbol': symbol, + 'cancelSize': cancel_size + } - def get_recent_orders(self, page=None, limit=None, **params): - """Get up to 1000 last orders in the last 24 hours. + return self._delete('hf/orders/cancel/{}'.format(order_id), True, data=dict(data, **params)) - https://www.kucoin.com/docs/rest/spot-trading/orders/get-recent-orders-list + def hf_cancel_orders_by_symbol(self, symbol, **params): + """Cancel all hf orders by symbol - :param page: (optional) Page to fetch - :type page: int - :param limit: (optional) Number of orders - :type limit: int + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/cancel-all-hf-orders-by-symbol + + :param symbol: Name of symbol e.g. ETH-USDT + :type symbol: string .. code:: python - orders = client.get_recent_orders() + res = client.hf_cancel_orders_by_symbol('ETH-USDT') :returns: ApiResponse - todo add the response example + .. code:: python + + todo add the response example :raises: KucoinResponseException, KucoinAPIException """ - data = {} - if page: - data['page'] = page - if limit: - data['limit'] = limit - - return self._get('limit/orders', True, data=dict(data, **params)) + data = { + 'symbol': symbol + } - def get_order(self, order_id): - """Get order details + return self._delete('hf/orders', True, data=dict(data, **params)) - https://docs.kucoin.com/#get-an-order + def hf_cancel_all_orders(self, **params): + """Cancel all hf orders - :param order_id: orderOid value - :type order_id: str + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/cancel-all-hf-orders .. code:: python - order = client.get_order('5c35c02703aa673ceec2a168') + res = client.hf_cancel_all_orders() :returns: ApiResponse .. code:: python { - "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, - "iceberge": false, - "visibleSize": "0", - "cancelAfter": 0, - "channel": "IOS", - "clientOid": null, - "remark": null, - "tags": null, - "isActive": false, - "cancelExist": false, - "createdAt": 1547026471000 + "succeedSymbols": [ + "ETH-USDT" + ], + "failedSymbols": [ + { + "symbol": "BTC-USDT", + "error": "can't cancel, system timeout" + } + ], } :raises: KucoinResponseException, KucoinAPIException """ - - return self._get('orders/{}'.format(order_id), True) + return self._delete('hf/orders/cancelAll', True, data=params) def hf_get_order(self, order_id, symbol): """Get hf order details by orderId @@ -3503,61 +4028,6 @@ def hf_get_order(self, order_id, symbol): return self._get('hf/orders/{}'.format(order_id), True, data=data) - def get_order_by_client_oid(self, client_oid): - """Get order details by clientOid - - https://docs.kucoin.com/#get-an-order - - :param client_oid: clientOid value - :type client_oid: str - - .. code:: python - - order = client.get_order_by_client_oid('6d539dc614db312') - - :returns: ApiResponse - - .. code:: python - - { - "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": "", - "stop": "", - "stopTriggered": false, - "stopPrice": "0", - "timeInForce": "GTC", - "postOnly": false, - "hidden": false, - "iceberg": false, - "visibleSize": "0", - "cancelAfter": 0, - "channel": "API", - "clientOid": "6d539dc614db312", - "remark": "", - "tags": "", - "isActive": true, - "cancelExist": false, - "createdAt": 1597051810000, - "tradeType": "TRADE" - } - - :raises: KucoinResponseException, KucoinAPIException - - """ - - return self._get('order/client-order/{}'.format(client_oid), True) - # Fill Endpoints def get_fills(self, order_id=None, symbol=None, side=None, order_type=None, @@ -4204,7 +4674,7 @@ def get_ws_endpoint(self, private=False): return self._post(path, signed) - def get_user_info (self): + def get_user_info(self): """Get account summary info https://www.kucoin.com/docs/rest/account/basic-info/get-account-summary-info From e12aa8efc38647c84011a80bde4239aa94ea9326 Mon Sep 17 00:00:00 2001 From: rayBastard Date: Tue, 12 Nov 2024 22:50:24 +0100 Subject: [PATCH 39/60] hf get methods added hf_get_active_orders hf_get_symbol_with_active_orders hf_get_completed_order_list hf_get_order_details hf_auto_cancel_order hf_get_auto_cancel_order hf_get_fills --- kucoin/client.py | 355 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 348 insertions(+), 7 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 1fcf452..9abe3f5 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -3205,6 +3205,8 @@ def get_order_by_client_oid(self, client_oid, **params): return self._get('order/client-order/{}'.format(client_oid), True, data=params) + # HF Order Endpoints + def hf_create_order(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, remark=None, time_in_force=None, cancel_after=None, post_only=None, hidden=None, iceberg=None, visible_size=None, tags=None, **params): @@ -3961,19 +3963,209 @@ def hf_cancel_all_orders(self, **params): """ return self._delete('hf/orders/cancelAll', True, data=params) - def hf_get_order(self, order_id, symbol): - """Get hf order details by orderId + def hf_get_active_orders(self, symbol, **params): + """Get a list of active hf orders - https://docs.kucoin.com/#get-hf-order-details-by-orderid + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/get-active-hf-orders-list - :param order_id: orderId value - :type order_id: str :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string .. code:: python - order = client.hf_get_order('5c35c02703aa673ceec2a168', 'KCS-BTC') + orders = client.hf_get_active_orders('ETH-USDT') + + :returns: ApiResponse + + .. code:: python + + { + "code" : "200000", + "data" : [ + "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" + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('hf/orders/active', True, data=dict(data, **params)) + + def hf_get_symbol_with_active_orders(self, **params): + """Get a list of symbols with active hf orders + + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/get-symbol-with-active-hf-orders-list + + .. code:: python + + orders = client.hf_get_symbol_with_active_orders() + + :returns: ApiResponse + + .. code:: python + + { + "success": true, + "code": "200", + "msg": "success", + "retry": false, + "data": { + "symbols": ["BTC-USDT"] + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + return self._get('hf/orders/active/symbols', True, data=params) + + def hf_get_completed_order_list(self, symbol, side=None, type=None, start=None, end=None, last_id=None, limit=None, **params): + """Get a list of completed hf orders + + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/get-hf-completed-order-list + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param side: (optional) buy or sell + :type side: string + :param type: (optional) limit, market, limit_stop or market_stop + :type type: string + :param start: (optional) Start time as unix timestamp + :type start: int + :param end: (optional) End time as unix timestamp + :type end: int + :param last_id: (optional) The last orderId of the last page + :type last_id: int + :param limit: (optional) Number of orders + :type limit: int + + .. code:: python + + orders = client.hf_get_completed_order_list('ETH-USDT') + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "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" + } + ] + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + if side: + data['side'] = side + if type: + data['type'] = type + if start: + data['startAt'] = start + if end: + data['endAt'] = end + if last_id: + data['lastId'] = last_id + if limit: + data['limit'] = limit + + return self._get('hf/orders/done', True, data=dict(data, **params)) + + def hf_get_order_details(self, order_id, symbol, **params): + """Get an hf order details + + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/get-hf-order-details-by-orderid + + :param order_id: OrderId + :type order_id: string + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + + .. code:: python + + order = client.hf_get_order_details('5bd6e9286d99522a52e458de', 'KCS-BTC') :returns: ApiResponse @@ -4026,7 +4218,72 @@ def hf_get_order(self, order_id, symbol): 'symbol': symbol } - return self._get('hf/orders/{}'.format(order_id), True, data=data) + return self._get('hf/orders/{}'.format(order_id), True, data=dict(data, **params)) + + def hf_auto_cancel_order(self, timeout, symbol=None, **params): + """Auto cancel a hf order + + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/auto-cancel-hf-order-setting + + :param timeout: The timeout period in ms + :type timeout: int + :param symbol: (optional) Name of symbol e.g. KCS-BTC + :type symbol: string + + .. code:: python + + res = client.hf_auto_cancel_order(60000) + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "currentTime": 1682010526, + "triggerTime": 1682010531 + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'timeout': timeout + } + + if symbol: + data['symbol'] = symbol + + return self._post('hf/orders/dead-cancel-all', True, data=dict(data, **params)) + + def hf_get_auto_cancel_order(self, **params): + """Get auto cancel setting + + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/auto-cancel-hf-order-setting-query + + .. code:: python + + res = client.hf_get_auto_cancel_order() + + :returns: ApiResponse + + .. code:: python + + { + "timeout": 5, + "symbols": "BTC-USDT", + "currentTime": 1682010526, + "triggerTime": 1682010531 + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + return self._get('hf/orders/dead-cancel-all', True, data=params) # Fill Endpoints @@ -4116,6 +4373,90 @@ def get_fills(self, order_id=None, symbol=None, side=None, order_type=None, return self._get('fills', True, data=data) + def hf_get_fills(self, symbol, order_id=None, side=None, type=None, start=None, end=None, last_id=None, limit=None, **params): + """Get a list of hf fills + + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/get-hf-filled-list + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param order_id: (optional) OrderId + :type order_id: string + :param side: (optional) buy or sell + :type side: string + :param type: (optional) limit, market, limit_stop or market_stop + :type type: string + :param start: (optional) Start time as unix timestamp + :type start: int + :param end: (optional) End time as unix timestamp + :type end: int + :param last_id: (optional) The last orderId of the last page + :type last_id: int + :param limit: (optional) Number of orders + :type limit: int + + .. code:: python + + fills = client.hf_get_fills('ETH-USDT') + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "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 + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + if order_id: + data['orderId'] = order_id + if side: + data['side'] = side + if type: + data['type'] = type + if start: + data['startAt'] = start + if end: + data['endAt'] = end + if last_id: + data['lastId'] = last_id + if limit: + data['limit'] = limit + + return self._get('hf/fills', True, data=dict(data, **params)) + # Market Endpoints def get_symbols(self, market=None, **params): From cef97cad701b0ec1aa4c7ec71d10430771782521 Mon Sep 17 00:00:00 2001 From: rayBastard Date: Tue, 12 Nov 2024 23:00:07 +0100 Subject: [PATCH 40/60] get_fills updated get_fills get_recent_fills --- kucoin/client.py | 129 ++++++++++++++++++++++++++++++++--------------- 1 file changed, 87 insertions(+), 42 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 9abe3f5..f397bf5 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -4287,61 +4287,62 @@ def hf_get_auto_cancel_order(self, **params): # Fill Endpoints - def get_fills(self, order_id=None, symbol=None, side=None, order_type=None, - start=None, end=None, page=None, limit=None, trade_type=None): + def get_fills(self, trade_type, order_id=None, symbol=None, side=None, type=None, start=None, end=None, page=None, limit=None, **params): """Get a list of recent fills. - https://docs.kucoin.com/#list-fills + https://www.kucoin.com/docs/rest/spot-trading/fills/get-filled-list - :param order_id: (optional) generated order id + :param trade_type: TRADE (Spot Trading), MARGIN_TRADE (Margin Trading), MARGIN_ISOLATED_TRADE (Isolated Margin Trading), TRADE as default. + :type trade_type: string + :param order_id: (optional) OrderId :type order_id: string :param symbol: (optional) Name of symbol e.g. KCS-BTC :type symbol: string :param side: (optional) buy or sell :type side: string - :param order_type: (optional) limit, market, limit_stop or market_stop - :type order_type: string - :param start: Start time as unix timestamp (optional) - :type start: string - :param end: End time as unix timestamp (optional) - :type end: string - :param trade_type: The type of trading : TRADE(Spot Trading), MARGIN_TRADE (Margin Trading). - :type trade_type: string - :param page: optional - Page to fetch + :param type: (optional) limit, market, limit_stop or market_stop + :type type: string + :param start: (optional) Start time as unix timestamp + :type start: int + :param end: (optional) End time as unix timestamp + :type end: int + :param page: (optional) Page number :type page: int - :param limit: optional - Number of orders + :param limit: (optional) Number of orders :type limit: int + .. code:: python - fills = client.get_fills() + fills = client.get_fills('TRADE') :returns: ApiResponse .. code:: python { - "currentPage":1, - "pageSize":1, - "totalNum":251915, - "totalPage":251915, - "items":[ + "currentPage": 1, + "pageSize": 1, + "totalNum": 251915, + "totalPage": 251915, + "items": [ { - "symbol":"BTC-USDT", - "tradeId":"5c35c02709e4f67d5266954e", - "orderId":"5c35c02703aa673ceec2a168", - "counterOrderId":"5c1ab46003aa676e487fa8e3", - "side":"buy", - "liquidity":"taker", - "forceTaker":true, - "price":"0.083", - "size":"0.8424304", - "funds":"0.0699217232", - "fee":"0", - "feeRate":"0", - "feeCurrency":"USDT", - "stop":"", - "type":"limit", - "createdAt":1547026472000 + "symbol": "BTC-USDT", + "tradeId": "5c35c02709e4f67d5266954e", + "orderId": "5c35c02703aa673ceec2a168", + "counterOrderId": "5c1ab46003aa676e487fa8e3", + "side": "buy", + "liquidity": "taker", + "forceTaker": true, + "price": "0.083", + "size": "0.8424304", + "funds": "0.0699217232", + "fee": "0", + "feeRate": "0", + "feeCurrency": "USDT", + "stop": "", + "type": "limit", + "createdAt": 1547026472000, + "tradeType": "TRADE" } ] } @@ -4350,7 +4351,9 @@ def get_fills(self, order_id=None, symbol=None, side=None, order_type=None, """ - data = {} + data = { + 'tradeType': trade_type + } if order_id: data['orderId'] = order_id @@ -4358,8 +4361,8 @@ def get_fills(self, order_id=None, symbol=None, side=None, order_type=None, data['symbol'] = symbol if side: data['side'] = side - if order_type: - data['type'] = order_type + if type: + data['type'] = type if start: data['startAt'] = start if end: @@ -4368,10 +4371,52 @@ def get_fills(self, order_id=None, symbol=None, side=None, order_type=None, data['currentPage'] = page if limit: data['pageSize'] = limit - if trade_type: - data['tradeType'] = trade_type - return self._get('fills', True, data=data) + return self._get('fills', False, data=dict(data, **params)) + + def get_recent_fills(self, **params): + """Get a list of recent fills. + + https://www.kucoin.com/docs/rest/spot-trading/fills/get-recent-filled-list + + .. code:: python + + fills = client.get_recent_fills() + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": [ + { + "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" + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + return self._get('limit/fills', True, data=params) def hf_get_fills(self, symbol, order_id=None, side=None, type=None, start=None, end=None, last_id=None, limit=None, **params): """Get a list of hf fills From 40bf6912dd830f3f4c0a100112704cdef45e69d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Wed, 13 Nov 2024 20:15:48 +0300 Subject: [PATCH 41/60] methods for stop orders added --- kucoin/client.py | 317 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 315 insertions(+), 2 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index f397bf5..7b1019c 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -4153,7 +4153,7 @@ def hf_get_completed_order_list(self, symbol, side=None, type=None, start=None, return self._get('hf/orders/done', True, data=dict(data, **params)) - def hf_get_order_details(self, order_id, symbol, **params): + def hf_get_order(self, order_id, symbol, **params): """Get an hf order details https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/get-hf-order-details-by-orderid @@ -4165,7 +4165,7 @@ def hf_get_order_details(self, order_id, symbol, **params): .. code:: python - order = client.hf_get_order_details('5bd6e9286d99522a52e458de', 'KCS-BTC') + order = client.hf_get_order('5bd6e9286d99522a52e458de', 'KCS-BTC') :returns: ApiResponse @@ -4285,6 +4285,319 @@ def hf_get_auto_cancel_order(self, **params): return self._get('hf/orders/dead-cancel-all', True, data=params) + def create_stop_order(self, symbol, type, side, stop_price, size=None, price=None, funds=None, client_oid=None, stp=None, + remark=None, time_in_force=None, cancel_after=None, post_only=None, + hidden=None, iceberg=None, visible_size=None, stop=None, trade_type=None, **params): + """Create a stop order + + https://www.kucoin.com/docs/rest/spot-trading/stop-order/place-order + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param type: order type (limit or market) + :type type: string + :param side: buy or sell + :type side: string + :param stop_price: Stop price + :type stop_price: string + :param size: (optional) Desired amount in base currency (required for limit order) + :type size: string + :param price: (optional) Price (required for limit order) + :type price: string + :param funds: (optional) Desired amount of quote currency to use (for market order only) + :type funds: string + :param client_oid: (optional) Unique order id (default flat_uuid()) + :type client_oid: string + :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) + :type stp: string + :param remark: (optional) remark for the order, max 100 utf8 characters + :type remark: string + :param time_in_force: (optional) GTC, GTT, IOC, or FOK - default is GTC (for limit order only) + :type time_in_force: string + :param cancel_after: (optional) time in ms to cancel after (for limit order only) + :type cancel_after: string + :param post_only: (optional) Post only flag (for limit order only) + :type post_only: bool + :param hidden: (optional) Hidden order flag (for limit order only) + :type hidden: bool + :param iceberg: (optional) Iceberg order flag (for limit order only) + :type iceberg: bool + :param visible_size: (optional) The maximum visible size of an iceberg order (for limit orders only) + :type visible_size: string + :param stop: (optional) stop type - loss or entry (default is loss) + :type stop: string + :param trade_type: (optional) TRADE (Spot Trading), MARGIN_TRADE (Margin Trading), MARGIN_ISOLATED_TRADE (Isolated Margin Trading), default is TRADE. + :type trade_type: string + + .. code:: python + + order = client.create_stop_order('ETH-USDT', Client.ORDER_LIMIT, Client.SIDE_BUY, stop_price=2100, size=20, price=2000) + order = client.create_order('ETH-USDT', Client.ORDER_MARKET, Client.SIDE_BUY, stop_price=2100, funds=20) + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "orderId": "672a249054d62a0007ae04b8", + "clientOid": "988a99edda5e496e95eb6e050c444994" + } + } + + :raises: KucoinResponseException, KucoinAPIException, MarketOrderException, LimitOrderException, KucoinRequestException + + """ + + if not client_oid: + client_oid = flat_uuid() + + data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, + time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) + + data['stopPrice'] = stop_price + if stop: + data['stop'] = stop + if trade_type: + data['tradeType'] = trade_type + + return self._post('stop-order', True, data=dict(data, **params)) + + def cancel_stop_order(self, order_id, **params): + """Cancel a stop order + + https://www.kucoin.com/docs/rest/spot-trading/stop-order/cancel-order-by-orderid + + :param order_id: Order id + :type order_id: string + + .. code:: python + + res = client.cancel_stop_order('5bd6e9286d99522a52e458de') + + :returns: ApiResponse + + .. code:: python + + { + "cancelledOrderIds": [ + "5bd6e9286d99522a52e458de" + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + KucoinAPIException If order_id is not found + + """ + + return self._delete('stop-order/{}'.format(order_id), True, data=params) + + def cancel_order_by_client_oid(self, client_oid, symbol=None, **params): + """Cancel a spot order by the clientOid + + https://www.kucoin.com/docs/rest/spot-trading/orders/cancel-order-by-clientoid + + :param client_oid: ClientOid + :type client_oid: string + :param symbol: (optional) Name of symbol e.g. ETH-USDT + :type symbol: string + + .. code:: python + + res = client.cancel_order_by_client_oid('6d539dc614db3') + + :returns: ApiResponse + + .. code:: python + + { + "cancelledOrderId": "5f311183c9b6d539dc614db3", + "clientOid": "6d539dc614db3" + } + + :raises: KucoinResponseException, KucoinAPIException + + KucoinAPIException If order_id is not found + + """ + + data = { + 'clientOid': client_oid + } + + if symbol: + data['symbol'] = symbol + + return self._delete('stop-order/cancelOrderByClientOid', True, data=dict(data, **params)) + + def cancel_all_stop_orders(self, symbol=None, trade_type=None, order_ids=None, **params): + """Cancel all stop orders + + https://www.kucoin.com/docs/rest/spot-trading/stop-order/cancel-stop-orders + + :param symbol: (optional) Name of symbol e.g. ETH-USDT + :type symbol: string + :param trade_type: (optional) The type of trading: + TRADE - spot trading, MARGIN_TRADE - cross margin trading, MARGIN_ISOLATED_TRADE - isolated margin trading + default is TRADE + :type trade_type: string + :param order_ids: (optional) Comma seperated order IDs (e.g. '5bd6e9286d99522a52e458de,5bd6e9286d99522a52e458df') + :type order_ids: string + + .. code:: python + + res = client.cancel_all_stop_orders() + + :returns: ApiResponse + + .. code:: python + + { + "cancelledOrderIds": [ + "5bd6e9286d99522a52e458de" + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + data = {} + if symbol: + data['symbol'] = symbol + if trade_type: + data['tradeType'] = trade_type + if order_ids: + data['orderIds'] = order_ids + + return self._delete('stop-order/cancel', True, data=dict(data, **params)) + + def get_stop_orders(self, symbol=None, side=None, order_type=None, start=None, end=None, + page=None, limit=None, trade_type=None, order_ids=None, stop=None, **params): + """Get list of stop orders + + https://www.kucoin.com/docs/rest/spot-trading/stop-order/get-stop-orders-list + + :param symbol: (optional) Name of symbol e.g. KCS-BTC + :type symbol: string + :param side: (optional) buy or sell + :type side: string + :param order_type: (optional) limit, market, limit_stop or market_stop + :type order_type: string + :param trade_type: (optional) The type of trading : + TRADE - spot trading, MARGIN_TRADE - cross margin trading, MARGIN_ISOLATED_TRADE - isolated margin trading + default is TRADE + :type trade_type: string + :param start: (optional) Start time as unix timestamp + :type start: string + :param end: (optional) End time as unix timestamp + :type end: string + :param page: (optional) Page to fetch + :type page: int + :param limit: (optional) Number of orders + :type limit: int + :param order_ids: (optional) Comma seperated order IDs (e.g. '5bd6e9286d99522a52e458de,5bd6e9286d99522a52e458df') + :type order_ids: string + :param stop: (optional) stop (stop loss order) or oco (oco order) todo check this parameter + :type stop: string + + .. code:: python + + orders = client.get_stop_orders(symbol='KCS-BTC', side='sell') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + + if symbol: + data['symbol'] = symbol + if side: + data['side'] = side + if order_type: + data['type'] = order_type + if start: + data['startAt'] = start + if end: + data['endAt'] = end + if page: + data['currentPage'] = page + if limit: + data['pageSize'] = limit + if trade_type: + data['tradeType'] = trade_type + if order_ids: + data['orderIds'] = order_ids + if stop: + data['stop'] = stop + + return self._get('stop-order', True, data=dict(data, **params)) + + def get_stop_order(self, order_id, **params): + """Get stop order details + + https://www.kucoin.com/docs/rest/spot-trading/stop-order/get-order-details-by-orderid + + :param order_id: orderOid value + :type order_id: str + + .. code:: python + + order = client.get_stop_order('5c35c02703aa673ceec2a168') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + return self._get('stop-order/{}'.format(order_id), True, data=params) + + def get_stop_order_by_client_oid(self, client_oid, symbol=None, **params): + """Get stop order details by clientOid + + https://www.kucoin.com/docs/rest/spot-trading/stop-order/get-order-details-by-clientoid + + :param client_oid: clientOid value + :type client_oid: str + :param symbol: (optional) Name of symbol e.g. ETH-USDT + :type symbol: string + + .. code:: python + + order = client.get_stop_order_by_client_oid('6d539dc614db312') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'clientOid': client_oid + } + + if symbol: + data['symbol'] = symbol + + return self._get('stop-order/queryOrderByClientOid', True, data=dict(data, **params)) + # Fill Endpoints def get_fills(self, trade_type, order_id=None, symbol=None, side=None, type=None, start=None, end=None, page=None, limit=None, **params): From 3cfa9e4fe96835f3bc9ff5fbdf277fa2b8ad5744 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Wed, 13 Nov 2024 21:00:26 +0300 Subject: [PATCH 42/60] methods for oco orders added --- kucoin/client.py | 257 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 257 insertions(+) diff --git a/kucoin/client.py b/kucoin/client.py index 7b1019c..cffc4b5 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -4598,6 +4598,263 @@ def get_stop_order_by_client_oid(self, client_oid, symbol=None, **params): return self._get('stop-order/queryOrderByClientOid', True, data=dict(data, **params)) + def oco_create_order(self, symbol, side, size, price, stop_price, limit_price, client_oid=None, remark=None, **params): + """Create an OCO order + + https://www.kucoin.com/docs/rest/spot-trading/oco-order/place-order + + :param symbol: Name of symbol e.g. ETH-USDT + :type symbol: string + :param side: buy or sell + :type side: string + :param size: Desired amount in base currency + :type size: string + :param price: price + :type price: string + :param stop_price: trigger price + :type stop_price: string + :param limit_price: limit order price after take-profit and stop-loss are triggered + :type limit_price: string + :param client_oid: (optional) Unique order id (default flat_uuid()) + :type client_oid: string + :param remark: (optional) remark for the order, max 100 utf8 characters + :type remark: string + + .. code:: python + + order = client.oco_create_order('ETH-USDT', Client.SIDE_BUY, size=20, price=2000, stop_price=2100, limit_price=2200) + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol, + 'side': side, + 'size': size, + 'price': price, + 'stopPrice': stop_price, + 'limitPrice': limit_price + } + + if not client_oid: + client_oid = flat_uuid() + else: + data['clientOid'] = client_oid + + if remark: + data['remark'] = remark + + return self._post('oco/order', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def oco_cancel_order(self, order_id, **params): + """Cancel an oco order + + https://www.kucoin.com/docs/rest/spot-trading/oco-order/cancel-order-by-orderid + + :param order_id: Order id + :type order_id: string + + .. code:: python + + res = client.oco_cancel_order('5bd6e9286d99522a52e458de') + + :returns: ApiResponse + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + KucoinAPIException If order_id is not found + + """ + + return self._delete('oco/order/{}'.format(order_id), True, api_version=self.API_VERSION3, data=params) + + def oco_cancel_order_by_client_oid(self, client_oid, **params): + """Cancel a spot order by the clientOid + + https://www.kucoin.com/docs/rest/spot-trading/oco-order/cancel-order-by-clientoid + + :param client_oid: ClientOid + :type client_oid: string + + .. code:: python + + res = client.oco_cancel_order_by_client_oid('6d539dc614db3') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + KucoinAPIException If order_id is not found + + """ + + return self._delete('oco/client-order/{}'.format(client_oid), True, api_version=self.API_VERSION3, data=params) + + def oco_cancel_all_orders(self, symbol=None, order_ids=None, **params): + """Cancel all oco orders + + https://www.kucoin.com/docs/rest/spot-trading/oco-order/cancel-multiple-orders + + :param symbol: (optional) Name of symbol e.g. ETH-USDT + :type symbol: string + :param order_ids: (optional) Comma seperated order IDs (e.g. '5bd6e9286d99522a52e458de,5bd6e9286d99522a52e458df') + :type order_ids: string + + .. code:: python + + res = client.oco_cancel_all_orders() + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + data = {} + if symbol: + data['symbol'] = symbol + if order_ids: + data['orderIds'] = order_ids + + return self._delete('oco/orders', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def oco_get_order_info(self, order_id, **params): + """Get oco order information + for the order details use oco_get_order() + + https://www.kucoin.com/docs/rest/spot-trading/oco-order/get-order-info-by-orderid + + :param order_id: orderOid value + :type order_id: str + + .. code:: python + + order = client.oco_get_order_info('5c35c02703aa673ceec2a168') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + return self._get('oco/order/{}'.format(order_id), True, api_version=self.API_VERSION3, data=params) + + def oco_get_order(self, order_id, **params): + """Get oco order information + + https://www.kucoin.com/docs/rest/spot-trading/oco-order/get-order-details-by-orderid + + :param order_id: orderOid value + :type order_id: str + + .. code:: python + + order = client.oco_get_order('5c35c02703aa673ceec2a168') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + return self._get('oco/order/details/{}'.format(order_id), True, api_version=self.API_VERSION3, data=params) + + def oco_get_order_by_client_oid(self, client_oid, **params): + """Get oco order details by clientOid + + https://www.kucoin.com/docs/rest/spot-trading/oco-order/get-order-info-by-clientoid + + :param client_oid: clientOid value + :type client_oid: str + + .. code:: python + + order = client.oco_get_order_by_client_oid('6d539dc614db312') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + return self._get('oco/client-order/{}'.format(client_oid), True, api_version=self.API_VERSION3, data=params) + + def oco_get_orders(self, symbol=None, start=None, end=None, page=None, limit=None, order_ids=None, **params): + """Get list of oco orders + + https://www.kucoin.com/docs/rest/spot-trading/oco-order/get-order-list + + :param symbol: (optional) Name of symbol e.g. KCS-BTC + :type symbol: string + :param start: (optional) Start time as unix timestamp + :type start: string + :param end: (optional) End time as unix timestamp + :type end: string + :param page: (optional) Page to fetch + :type page: int + :param limit: (optional) Number of orders + :type limit: int + :param order_ids: (optional) Comma seperated order IDs (e.g. '5bd6e9286d99522a52e458de,5bd6e9286d99522a52e458df') + :type order_ids: string + + .. code:: python + + orders = client.oco_get_orders(symbol='KCS-BTC') + + :returns: ApiResponse + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + + if symbol: + data['symbol'] = symbol + if start: + data['startAt'] = start + if end: + data['endAt'] = end + if page: + data['currentPage'] = page + if limit: + data['pageSize'] = limit + if order_ids: + data['orderIds'] = order_ids + + return self._get('oco/orders', True, api_version=self.API_VERSION3, data=dict(data, **params)) + # Fill Endpoints def get_fills(self, trade_type, order_id=None, symbol=None, side=None, type=None, start=None, end=None, page=None, limit=None, **params): From 8d86abe21db95d9ae3023aebf0a72e774b6c4d8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Thu, 14 Nov 2024 18:47:23 +0300 Subject: [PATCH 43/60] methods for margin and hf_margin orders added --- kucoin/client.py | 950 ++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 818 insertions(+), 132 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index cffc4b5..4c4ca7f 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -3749,7 +3749,7 @@ def hf_cancel_order(self, order_id, symbol, **params): .. code:: python - res = client.hf_cancel_order_by_order_id('5bd6e9286d99522a52e458de', 'KCS-BTC') + res = client.hf_cancel_order('5bd6e9286d99522a52e458de', 'KCS-BTC') :returns: ApiResponse @@ -4058,7 +4058,7 @@ def hf_get_symbol_with_active_orders(self, **params): return self._get('hf/orders/active/symbols', True, data=params) - def hf_get_completed_order_list(self, symbol, side=None, type=None, start=None, end=None, last_id=None, limit=None, **params): + def hf_get_completed_orders(self, symbol, side=None, type=None, start=None, end=None, last_id=None, limit=None, **params): """Get a list of completed hf orders https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/get-hf-completed-order-list @@ -4080,7 +4080,7 @@ def hf_get_completed_order_list(self, symbol, side=None, type=None, start=None, .. code:: python - orders = client.hf_get_completed_order_list('ETH-USDT') + orders = client.hf_get_completed_orders('ETH-USDT') :returns: ApiResponse @@ -4154,7 +4154,7 @@ def hf_get_completed_order_list(self, symbol, side=None, type=None, start=None, return self._get('hf/orders/done', True, data=dict(data, **params)) def hf_get_order(self, order_id, symbol, **params): - """Get an hf order details + """Get an hf order details by the orderId https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/get-hf-order-details-by-orderid @@ -4220,6 +4220,36 @@ def hf_get_order(self, order_id, symbol, **params): return self._get('hf/orders/{}'.format(order_id), True, data=dict(data, **params)) + def hf_get_order_by_client_oid(self, client_oid, symbol, **params): + """Get hf order details by clientOid + + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/get-hf-order-details-by-clientoid + + :param client_oid: clientOid value + :type client_oid: str + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + + .. code:: python + + order = client.hf_get_order_by_client_oid('6d539dc614db312', 'KCS-BTC') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('hf/orders/client-order/{}'.format(client_oid), True, data=dict(data, **params)) + def hf_auto_cancel_order(self, timeout, symbol=None, **params): """Auto cancel a hf order @@ -4789,7 +4819,7 @@ def oco_get_order_by_client_oid(self, client_oid, **params): https://www.kucoin.com/docs/rest/spot-trading/oco-order/get-order-info-by-clientoid :param client_oid: clientOid value - :type client_oid: str + :type client_oid: string .. code:: python @@ -4855,179 +4885,775 @@ def oco_get_orders(self, symbol=None, start=None, end=None, page=None, limit=Non return self._get('oco/orders', True, api_version=self.API_VERSION3, data=dict(data, **params)) - # Fill Endpoints - - def get_fills(self, trade_type, order_id=None, symbol=None, side=None, type=None, start=None, end=None, page=None, limit=None, **params): - """Get a list of recent fills. + def margin_create_order(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, + remark=None, time_in_force=None, cancel_after=None, post_only=None, hidden=None, + iceberg=None, visible_size=None, margin_model=None, auto_borrow=None, auto_repay=None, **params): + """Create a margin order - https://www.kucoin.com/docs/rest/spot-trading/fills/get-filled-list + https://www.kucoin.com/docs/rest/margin-trading/orders/place-margin-order - :param trade_type: TRADE (Spot Trading), MARGIN_TRADE (Margin Trading), MARGIN_ISOLATED_TRADE (Isolated Margin Trading), TRADE as default. - :type trade_type: string - :param order_id: (optional) OrderId - :type order_id: string - :param symbol: (optional) Name of symbol e.g. KCS-BTC + :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string - :param side: (optional) buy or sell - :type side: string - :param type: (optional) limit, market, limit_stop or market_stop + :param type: order type (limit or market) :type type: string - :param start: (optional) Start time as unix timestamp - :type start: int - :param end: (optional) End time as unix timestamp - :type end: int - :param page: (optional) Page number - :type page: int - :param limit: (optional) Number of orders - :type limit: int + :param side: buy or sell + :type side: string + :param size: (optional) Desired amount in base currency (required for limit order) + :type size: string + :param price: (optional) Price (required for limit order) + :type price: string + :param funds: (optional) Desired amount of quote currency to use (for market order only) + :type funds: string + :param client_oid: (optional) Unique order id (default flat_uuid()) + :type client_oid: string + :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) + :type stp: string + :param remark: (optional) remark for the order, max 100 utf8 characters + :type remark: string + :param time_in_force: (optional) GTC, GTT, IOC, or FOK - default is GTC (for limit order only) + :type time_in_force: string + :param cancel_after: (optional) time in ms to cancel after (for limit order only) + :type cancel_after: string + :param post_only: (optional) Post only flag (for limit order only) + :type post_only: bool + :param hidden: (optional) Hidden order flag (for limit order only) + :type hidden: bool + :param iceberg: (optional) Iceberg order flag (for limit order only) + :type iceberg: bool + :param visible_size: (optional) The maximum visible size of an iceberg order (for limit orders only) + :type visible_size: string + :param margin_model: (optional) cross or isolated (default is cross) + :type margin_model: string + :param auto_borrow: (optional) auto borrow flag (default is False). If true the system will first borrow you funds + at the optimal interest rate and then place an order for you. Currently autoBorrow parameter + only supports cross mode, not isolated mode. When add this param, stop profit and stop loss are not supported, + if it is a sell order, the size must be passed + :type auto_borrow: bool + :param auto_repay: (optional) auto repay flag (default is False). Automatically repay when placing an order, + that is, the system automatically triggers repayment after the order is completed. + The maximum currency repayment amount is the trade amount. + The same order does not support the simultaneous use of autoBorrow and autoRepay. .. code:: python - fills = client.get_fills('TRADE') + order = client.margin_create_order('ETH-USDT', Client.ORDER_LIMIT, Client.SIDE_BUY, size=20, price=2000) + order = client.margin_create_order('ETH-USDT', Client.ORDER_MARKET, Client.SIDE_BUY, funds=20) :returns: ApiResponse .. code:: python - { - "currentPage": 1, - "pageSize": 1, - "totalNum": 251915, - "totalPage": 251915, - "items": [ - { - "symbol": "BTC-USDT", - "tradeId": "5c35c02709e4f67d5266954e", - "orderId": "5c35c02703aa673ceec2a168", - "counterOrderId": "5c1ab46003aa676e487fa8e3", - "side": "buy", - "liquidity": "taker", - "forceTaker": true, - "price": "0.083", - "size": "0.8424304", - "funds": "0.0699217232", - "fee": "0", - "feeRate": "0", - "feeCurrency": "USDT", - "stop": "", - "type": "limit", - "createdAt": 1547026472000, - "tradeType": "TRADE" - } - ] - } + todo add the response example - :raises: KucoinResponseException, KucoinAPIException + :raises: KucoinResponseException, KucoinAPIException, MarketOrderException, LimitOrderException, KucoinRequestException """ - data = { - 'tradeType': trade_type - } + if not client_oid: + client_oid = flat_uuid() - if order_id: - data['orderId'] = order_id - if symbol: - data['symbol'] = symbol - if side: - data['side'] = side - if type: - data['type'] = type - if start: - data['startAt'] = start - if end: - data['endAt'] = end - if page: - data['currentPage'] = page - if limit: - data['pageSize'] = limit + data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, + time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) - return self._get('fills', False, data=dict(data, **params)) + if margin_model: + data['marginModel'] = margin_model + if auto_borrow and auto_repay: + raise KucoinRequestException('auto_borrow and auto_repay cannot be used together') + if auto_borrow: + data['autoBorrow'] = auto_borrow + if auto_repay: + data['autoRepay'] = auto_repay - def get_recent_fills(self, **params): - """Get a list of recent fills. + return self._post('margin/order', True, data=dict(data, **params)) - https://www.kucoin.com/docs/rest/spot-trading/fills/get-recent-filled-list + def margin_create_test_order(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, + remark=None, time_in_force=None, cancel_after=None, post_only=None, hidden=None, + iceberg=None, visible_size=None, margin_model=None, auto_borrow=None, auto_repay=None, **params): + """Create a margin test order + + https://www.kucoin.com/docs/rest/margin-trading/orders/place-margin-order-test + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param type: order type (limit or market) + :type type: string + :param side: buy or sell + :type side: string + :param size: (optional) Desired amount in base currency (required for limit order) + :type size: string + :param price: (optional) Price (required for limit order) + :type price: string + :param funds: (optional) Desired amount of quote currency to use (for market order only) + :type funds: string + :param client_oid: (optional) Unique order id (default flat_uuid()) + :type client_oid: string + :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) + :type stp: string + :param remark: (optional) remark for the order, max 100 utf8 characters + :type remark: string + :param time_in_force: (optional) GTC, GTT, IOC, or FOK - default is GTC (for limit order only) + :type time_in_force: string + :param cancel_after: (optional) time in ms to cancel after (for limit order only) + :type cancel_after: string + :param post_only: (optional) Post only flag (for limit order only) + :type post_only: bool + :param hidden: (optional) Hidden order flag (for limit order only) + :type hidden: bool + :param iceberg: (optional) Iceberg order flag (for limit order only) + :type iceberg: bool + :param visible_size: (optional) The maximum visible size of an iceberg order (for limit orders only) + :type visible_size: string + :param margin_model: (optional) cross or isolated (default is cross) + :type margin_model: string + :param auto_borrow: (optional) auto borrow flag (default is False). If true the system will first borrow you funds + at the optimal interest rate and then place an order for you. Currently autoBorrow parameter + only supports cross mode, not isolated mode. When add this param, stop profit and stop loss are not supported, + if it is a sell order, the size must be passed + :type auto_borrow: bool + :param auto_repay: (optional) auto repay flag (default is False). Automatically repay when placing an order, + that is, the system automatically triggers repayment after the order is completed. + The maximum currency repayment amount is the trade amount. + The same order does not support the simultaneous use of autoBorrow and autoRepay. .. code:: python - fills = client.get_recent_fills() + order = client.margin_create_test_order('ETH-USDT', Client.ORDER_LIMIT, Client.SIDE_BUY, size=20, price=2000) + order = client.margin_create_test_order('ETH-USDT', Client.ORDER_MARKET, Client.SIDE_BUY, funds=20) :returns: ApiResponse .. code:: python - { - "code": "200000", - "data": [ - { - "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" - } - ] - } + todo add the response example - :raises: KucoinResponseException, KucoinAPIException + :raises: KucoinResponseException, KucoinAPIException, MarketOrderException, LimitOrderException, KucoinRequestException """ - return self._get('limit/fills', True, data=params) + if not client_oid: + client_oid = flat_uuid() - def hf_get_fills(self, symbol, order_id=None, side=None, type=None, start=None, end=None, last_id=None, limit=None, **params): - """Get a list of hf fills + data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, + time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) - https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/get-hf-filled-list + if margin_model: + data['marginModel'] = margin_model + if auto_borrow and auto_repay: + raise KucoinRequestException('auto_borrow and auto_repay cannot be used together') + if auto_borrow: + data['autoBorrow'] = auto_borrow + if auto_repay: + data['autoRepay'] = auto_repay + + return self._post('margin/order/test', True, data=dict(data, **params)) + + def hf_margin_create_order(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, + remark=None, time_in_force=None, cancel_after=None, post_only=None, hidden=None, + iceberg=None, visible_size=None, is_isolated=None, auto_borrow=None, auto_repay=None, **params): + """Create an hf margin order + + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/place-hf-order :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string - :param order_id: (optional) OrderId - :type order_id: string - :param side: (optional) buy or sell - :type side: string - :param type: (optional) limit, market, limit_stop or market_stop + :param type: order type (limit or market) :type type: string - :param start: (optional) Start time as unix timestamp - :type start: int - :param end: (optional) End time as unix timestamp - :type end: int - :param last_id: (optional) The last orderId of the last page - :type last_id: int - :param limit: (optional) Number of orders - :type limit: int + :param side: buy or sell + :type side: string + :param size: (optional) Desired amount in base currency (required for limit order) + :type size: string + :param price: (optional) Price (required for limit order) + :type price: string + :param funds: (optional) Desired amount of quote currency to use (for market order only) + :type funds: string + :param client_oid: (optional) Unique order id (default flat_uuid()) + :type client_oid: string + :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) + :type stp: string + :param remark: (optional) remark for the order, max 100 utf8 characters + :type remark: string + :param time_in_force: (optional) GTC, GTT, IOC, or FOK - default is GTC (for limit order only) + :type time_in_force: string + :param cancel_after: (optional) time in ms to cancel after (for limit order only) + :type cancel_after: string + :param post_only: (optional) Post only flag (for limit order only) + :type post_only: bool + :param hidden: (optional) Hidden order flag (for limit order only) + :type hidden: bool + :param iceberg: (optional) Iceberg order flag (for limit order only) + :type iceberg: bool + :param visible_size: (optional) The maximum visible size of an iceberg order (for limit orders only) + :type visible_size: string + :param is_isolated: (optional) True for isolated margin, False for cross margin (default is False) + :type margin_model: bool + :param auto_borrow: (optional) auto borrow flag (default is False). + When Margin HFTrading Account has inefficient balance, + System autoborrows inefficient assets and opens positions + according to the lowest market interest rate. + :type auto_borrow: bool + :param auto_repay: (optional) auto repay flag (default is False). + AutoPay allows returning borrowed assets when you close a position. + System automatically triggers the repayment and the maximum repayment + amount equals to the filled-order amount. .. code:: python - fills = client.hf_get_fills('ETH-USDT') + order = client.hf_margin_create_order('ETH-USDT', Client.ORDER_LIMIT, Client.SIDE_BUY, size=20, price=2000) + order = client.hf_margin_create_order('ETH-USDT', Client.ORDER_MARKET, Client.SIDE_BUY, funds=20) :returns: ApiResponse .. code:: python - { - "code": "200000", - "data": { - "items": [ - { - "id": 2678765568, - "symbol": "BTC-ETC", - "tradeId": 616179312641, - "orderId": "6306cf6e27ecbe0001e1e03a", - "counterOrderId": "6306cf4027ecbe0001e1df4d", + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException, MarketOrderException, LimitOrderException, KucoinRequestException + + """ + + if not client_oid: + client_oid = flat_uuid() + + data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, + time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) + + if is_isolated: + data['isIsolated'] = is_isolated # todo check this parameter for margin_create_order + if auto_borrow: + data['autoBorrow'] = auto_borrow + if auto_repay: + data['autoRepay'] = auto_repay + + return self._post('hf/margin/order', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def hf_margin_create_test_order(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, + remark=None, time_in_force=None, cancel_after=None, post_only=None, hidden=None, + iceberg=None, visible_size=None, is_isolated=None, auto_borrow=None, auto_repay=None, **params): + """Create an hf margin test order + + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/place-hf-order-test + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param type: order type (limit or market) + :type type: string + :param side: buy or sell + :type side: string + :param size: (optional) Desired amount in base currency (required for limit order) + :type size: string + :param price: (optional) Price (required for limit order) + :type price: string + :param funds: (optional) Desired amount of quote currency to use (for market order only) + :type funds: string + :param client_oid: (optional) Unique order id (default flat_uuid()) + :type client_oid: string + :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) + :type stp: string + :param remark: (optional) remark for the order, max 100 utf8 characters + :type remark: string + :param time_in_force: (optional) GTC, GTT, IOC, or FOK - default is GTC (for limit order only) + :type time_in_force: string + :param cancel_after: (optional) time in ms to cancel after (for limit order only) + :type cancel_after: string + :param post_only: (optional) Post only flag (for limit order only) + :type post_only: bool + :param hidden: (optional) Hidden order flag (for limit order only) + :type hidden: bool + :param iceberg: (optional) Iceberg order flag (for limit order only) + :type iceberg: bool + :param visible_size: (optional) The maximum visible size of an iceberg order (for limit orders only) + :type visible_size: string + :param is_isolated: (optional) True for isolated margin, False for cross margin (default is False) + :type margin_model: bool + :param auto_borrow: (optional) auto borrow flag (default is False). + When Margin HFTrading Account has inefficient balance, + System autoborrows inefficient assets and opens positions + according to the lowest market interest rate. + :type auto_borrow: bool + :param auto_repay: (optional) auto repay flag (default is False). + AutoPay allows returning borrowed assets when you close a position. + System automatically triggers the repayment and the maximum repayment + amount equals to the filled-order amount. + + .. code:: python + + order = client.hf_margin_create_test_order('ETH-USDT', Client.ORDER_LIMIT, Client.SIDE_BUY, size=20, price=2000) + order = client.hf_margin_create_test_order('ETH-USDT', Client.ORDER_MARKET, Client.SIDE_BUY, funds=20) + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException, MarketOrderException, LimitOrderException, KucoinRequestException + + """ + + if not client_oid: + client_oid = flat_uuid() + + data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, + time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) + + if is_isolated: + data['isIsolated'] = is_isolated # todo check this parameter for margin_create_order + if auto_borrow: + data['autoBorrow'] = auto_borrow + if auto_repay: + data['autoRepay'] = auto_repay + + return self._post('hf/margin/order/test', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def hf_margin_cancel_order(self, order_id, symbol, **params): + """Cancel an hf margin order by the orderId + + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/cancel-hf-order-by-orderid + + :param order_id: OrderId + :type order_id: string + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + + .. code:: python + + res = client.hf_margin_cancel_order('5bd6e9286d99522a52e458de', 'KCS-BTC') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + KucoinAPIException If order_id is not found + + """ + + data = { + 'symbol': symbol + } + + return self._delete('hf/margin/orders/{}'.format(order_id), True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def hf_margin_cancel_order_by_client_oid(self, client_oid, symbol, **params): + """Cancel a hf margin order by the clientOid + + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/cancel-hf-order-by-clientoid + + :param client_oid: ClientOid + :type client_oid: string + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + + .. code:: python + + res = client.hf_margin_cancel_order_by_client_oid('6d539dc614db3', 'KCS-BTC') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + KucoinAPIException If order_id is not found + + """ + + data = { + 'symbol': symbol + } + + return self._delete('hf/margin/orders/client-order/{}'.format(client_oid), True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def hf_margin_cancel_orders_by_symbol(self, symbol, trade_type, **params): + """Cancel all hf margin orders by symbol + + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/cancel-all-hf-orders-by-symbol + + :param symbol: Name of symbol e.g. ETH-USDT + :type symbol: string + :param trade_type: MARGIN_TRADE (Margin Trading) or MARGIN_ISOLATED_TRADE (Isolated Margin Trading) + :type trade_type: string + + .. code:: python + + res = client.hf_margin_cancel_orders_by_symbol('ETH-USDT') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol, + 'tradeType': trade_type + } + + return self._delete('hf/margin/orders', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def hf_margin_get_active_orders(self, symbol, trade_type, **params): + """Get a list of active hf margin orders + + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-active-hf-orders-list + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param trade_type: MARGIN_TRADE (Margin Trading) or MARGIN_ISOLATED_TRADE (Isolated Margin Trading) + :type trade_type: string + + .. code:: python + + orders = client.hf_margin_get_active_orders('ETH-USDT') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol, + 'tradeType': trade_type + } + + return self._get('hf/margin/orders/active', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def hf_margin_get_completed_orders(self, symbol, trade_type, side=None, type=None, start=None, end=None, last_id=None, limit=None, **params): + """Get a list of completed hf margin orders + + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-hf-filled-list + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param trade_type: MARGIN_TRADE (Margin Trading) or MARGIN_ISOLATED_TRADE (Isolated Margin Trading) + :type trade_type: string + :param side: (optional) buy or sell + :type side: string + :param type: (optional) limit, market, limit_stop or market_stop + :type type: string + :param start: (optional) Start time as unix timestamp + :type start: int + :param end: (optional) End time as unix timestamp + :type end: int + :param last_id: (optional) The last orderId of the last page + :type last_id: int + :param limit: (optional) Number of orders + :type limit: int + + .. code:: python + + orders = client.hf_margin_get_completed_orders('ETH-USDT', 'MARGIN_ISOLATED_TRADE') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol, + 'tradeType': trade_type + } + + if side: + data['side'] = side + if type: + data['type'] = type + if start: + data['startAt'] = start + if end: + data['endAt'] = end + if last_id: + data['lastId'] = last_id + if limit: + data['limit'] = limit + + return self._get('hf/margin/orders/done', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def hf_margin_get_order(self, order_id, symbol, **params): + """Get an hf margin order details by the orderId + + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-hf-order-details-by-orderid + + :param order_id: OrderId + :type order_id: string + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + + .. code:: python + + order = client.hf_get_order('5bd6e9286d99522a52e458de', 'KCS-BTC') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('hf/margin/orders/{}'.format(order_id), True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def hf_get_order_by_client_oid(self, client_oid, symbol, **params): + """Get hf margin order details by clientOid + + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-hf-order-details-by-clientoid + + :param client_oid: clientOid value + :type client_oid: str + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + + .. code:: python + + order = client.hf_get_order_by_client_oid('6d539dc614db312', 'KCS-BTC') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('hf/margin/orders/client-order/{}'.format(client_oid), True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def hf_margin_get_symbol_with_active_orders(self, trade_type, **params): + """Get a list of symbols with active hf margin orders + + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-active-hf-order-symbols + + :param trade_type: MARGIN_TRADE (Margin Trading) or MARGIN_ISOLATED_TRADE (Isolated Margin Trading) + :type trade_type: string + + .. code:: python + + orders = client.hf_margin_get_symbol_with_active_orders('MARGIN_TRADE') + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "symbolSize": 1, + "symbols": ["ADA-USDT"] + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'tradeType': trade_type + } + + return self._get('hf/margin/order/active/symbols', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + # Fill Endpoints + + def get_fills(self, trade_type, order_id=None, symbol=None, side=None, type=None, start=None, end=None, page=None, limit=None, **params): + """Get a list of recent fills. + + https://www.kucoin.com/docs/rest/spot-trading/fills/get-filled-list + + :param trade_type: TRADE (Spot Trading), MARGIN_TRADE (Margin Trading), MARGIN_ISOLATED_TRADE (Isolated Margin Trading), TRADE as default. + :type trade_type: string + :param order_id: (optional) OrderId + :type order_id: string + :param symbol: (optional) Name of symbol e.g. KCS-BTC + :type symbol: string + :param side: (optional) buy or sell + :type side: string + :param type: (optional) limit, market, limit_stop or market_stop + :type type: string + :param start: (optional) Start time as unix timestamp + :type start: int + :param end: (optional) End time as unix timestamp + :type end: int + :param page: (optional) Page number + :type page: int + :param limit: (optional) Number of orders + :type limit: int + + .. code:: python + + fills = client.get_fills('TRADE') + + :returns: ApiResponse + + .. code:: python + + { + "currentPage": 1, + "pageSize": 1, + "totalNum": 251915, + "totalPage": 251915, + "items": [ + { + "symbol": "BTC-USDT", + "tradeId": "5c35c02709e4f67d5266954e", + "orderId": "5c35c02703aa673ceec2a168", + "counterOrderId": "5c1ab46003aa676e487fa8e3", + "side": "buy", + "liquidity": "taker", + "forceTaker": true, + "price": "0.083", + "size": "0.8424304", + "funds": "0.0699217232", + "fee": "0", + "feeRate": "0", + "feeCurrency": "USDT", + "stop": "", + "type": "limit", + "createdAt": 1547026472000, + "tradeType": "TRADE" + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'tradeType': trade_type + } + + if order_id: + data['orderId'] = order_id + if symbol: + data['symbol'] = symbol + if side: + data['side'] = side + if type: + data['type'] = type + if start: + data['startAt'] = start + if end: + data['endAt'] = end + if page: + data['currentPage'] = page + if limit: + data['pageSize'] = limit + + return self._get('fills', False, data=dict(data, **params)) + + def get_recent_fills(self, **params): + """Get a list of recent fills. + + https://www.kucoin.com/docs/rest/spot-trading/fills/get-recent-filled-list + + .. code:: python + + fills = client.get_recent_fills() + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": [ + { + "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" + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + return self._get('limit/fills', True, data=params) + + def hf_get_fills(self, symbol, order_id=None, side=None, type=None, start=None, end=None, last_id=None, limit=None, **params): + """Get a list of hf fills + + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/get-hf-filled-list + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param order_id: (optional) OrderId + :type order_id: string + :param side: (optional) buy or sell + :type side: string + :param type: (optional) limit, market, limit_stop or market_stop + :type type: string + :param start: (optional) Start time as unix timestamp + :type start: int + :param end: (optional) End time as unix timestamp + :type end: int + :param last_id: (optional) The last orderId of the last page + :type last_id: int + :param limit: (optional) Number of orders + :type limit: int + + .. code:: python + + fills = client.hf_get_fills('ETH-USDT') + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "items": [ + { + "id": 2678765568, + "symbol": "BTC-ETC", + "tradeId": 616179312641, + "orderId": "6306cf6e27ecbe0001e1e03a", + "counterOrderId": "6306cf4027ecbe0001e1df4d", "side": "buy", "liquidity": "taker", "forceTaker": false, @@ -5072,6 +5698,66 @@ def hf_get_fills(self, symbol, order_id=None, side=None, type=None, start=None, return self._get('hf/fills', True, data=dict(data, **params)) + def hf_margin_get_fills(self, symbol, trade_type, order_id=None, side=None, type=None, start=None, end=None, last_id=None, limit=None, **params): + """Get a list of hf fills + + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-hf-transaction-records + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param trade_type: MARGIN_TRADE (Margin Trading) or MARGIN_ISOLATED_TRADE (Isolated Margin Trading) + :type trade_type: string + :param order_id: (optional) OrderId + :type order_id: string + :param side: (optional) buy or sell + :type side: string + :param type: (optional) limit, market, limit_stop or market_stop + :type type: string + :param start: (optional) Start time as unix timestamp + :type start: int + :param end: (optional) End time as unix timestamp + :type end: int + :param last_id: (optional) The last orderId of the last page + :type last_id: int + :param limit: (optional) Number of orders + :type limit: int + + .. code:: python + + fills = client.hf_get_fills('ETH-USDT') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol, + 'tradeType': trade_type + } + + if order_id: + data['orderId'] = order_id + if side: + data['side'] = side + if type: + data['type'] = type + if start: + data['startAt'] = start + if end: + data['endAt'] = end + if last_id: + data['lastId'] = last_id + if limit: + data['limit'] = limit + + return self._get('hf/margin/fills', True, api_version=self.API_VERSION3, data=dict(data, **params)) + # Market Endpoints def get_symbols(self, market=None, **params): From 540aa1bfdda71db47f95a9ab7977ab48438736bb Mon Sep 17 00:00:00 2001 From: rayBastard Date: Sun, 17 Nov 2024 18:51:25 +0100 Subject: [PATCH 44/60] margin info endpoints added margin_get_leverage_token_info margin_get_all_trading_pairs_mark_prices margin_get_mark_price margin_get_config margin_get_cross_isolated_risk_limit_config --- kucoin/client.py | 1854 ++++++++++++++++++++++++++-------------------- 1 file changed, 1045 insertions(+), 809 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 4c4ca7f..81f762a 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -480,6 +480,519 @@ def get_currency(self, currency, chain=None, **params): return self._get('currencies/{}'.format(currency), False, api_version=self.API_VERSION3, data=dict({'chain': chain}, **params)) + # Market Endpoints + + def get_symbols(self, market=None, **params): + """Get a list of available currency pairs for trading. + + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-symbols-list + + :param market: (optional) Name of market e.g. BTC + :type market: string + + .. code:: python + + symbols = client.get_symbols() + symbols = client.get_symbols('USDS') + + :returns: ApiResponse + + .. code:: python + + [ + { + "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 + }, + { + "symbol": "VET-USDT", + "name": "VET-USDT", + "baseCurrency": "VET", + "quoteCurrency": "USDT", + "feeCurrency": "USDT", + "market": "USDS", + "baseMinSize": "10", + "quoteMinSize": "0.01", + "baseMaxSize": "10000000000", + "quoteMaxSize": "99999999", + "baseIncrement": "0.0001", + "quoteIncrement": "0.000001", + "priceIncrement": "0.0000001", + "priceLimitRate": "0.1", + "minFunds": "0.1", + "isMarginEnabled": true, + "enableTrading": true + } + ] + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + if market: + data['market'] = market + + return self._get('symbols', False, api_version=self.API_VERSION2, data=dict(data, **params)) + + def get_symbol(self, symbol=None, **params): + """Get a symbol details for trading. + + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-symbol-detail + + :param symbol: (optional) Name of symbol e.g. KCS-BTC + :type symbol: string + + .. code:: python + + symbol = client.get_symbol('XLM-USDT') + + :returns: ApiResponse + + .. code:: python + + { + "data" : { + "quoteMinSize" : "0.1", + "quoteCurrency" : "USDT", + "feeCurrency" : "USDT", + "symbol" : "BTC-USDT", + "market" : "USDS", + "baseMaxSize" : "10000000000", + "baseIncrement" : "0.00000001", + "quoteIncrement" : "0.000001", + "priceIncrement" : "0.1", + "priceLimitRate" : "0.1", + "minFunds" : "0.1", + "isMarginEnabled" : true, + "enableTrading" : true, + "baseCurrency" : "BTC", + "baseMinSize" : "0.00001", + "name" : "BTC-USDT", + "quoteMaxSize" : "99999999" + }, + "code" : "200000" + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + if symbol: + data['symbol'] = symbol + + return self._get('symbol', False, api_version=self.API_VERSION2, data=dict(data, **params)) + + def get_ticker(self, symbol, **params): + """Get symbol ticker + + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-ticker + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + + .. code:: python + + ticker = client.get_ticker('ETH-BTC') + + :returns: ApiResponse + + .. code:: python + + { + "sequence": "1550467636704", + "price": "0.03715005", + "size": "0.17", + "bestAsk": "0.03715004", + "bestAskSize": "1.788", + "bestBid": "0.03710768", + "bestBidSize": "3.803", + "time": 1550653727731 + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + data = { + 'symbol': symbol + } + return self._get('market/orderbook/level1', False, data=dict(data, **params)) + + def get_tickers(self): + """Get symbol tickers + + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-all-tickers + + .. code:: python + + tickers = client.get_tickers() + + :returns: ApiResponse + + .. code:: python + + { + "time": 1602832092060, + "ticker": [ + { + "symbol": "BTC-USDT", // symbol + "symbolName": "BTC-USDT", // Name of trading pairs, it would change after renaming + "buy": "11328.9", // bestAsk + "sell": "11329", // bestBid + "bestBidSize": "0.1", + "bestAskSize": "1", + "changeRate": "-0.0055", // 24h change rate + "changePrice": "-63.6", // 24h change price + "high": "11610", // 24h highest price + "low": "11200", // 24h lowest price + "vol": "2282.70993217", // 24h volume,the aggregated trading volume in BTC + "volValue": "25984946.157790431", // 24h total, the trading volume in quote currency of last 24 hours + "last": "11328.9", // last price + "averagePrice": "11360.66065903", // 24h average transaction price yesterday + "takerFeeRate": "0.001", // Basic Taker Fee + "makerFeeRate": "0.001", // Basic Maker Fee + "takerCoefficient": "1", // Taker Fee Coefficient + "makerCoefficient": "1" // Maker Fee Coefficient + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + return self._get('market/allTickers', False) + + def get_24hr_stats(self, symbol, **params): + """Get 24hr stats for a symbol. Volume is in base currency units. open, high, low are in quote currency units. + + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-24hr-stats + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + + .. code:: python + + stats = client.get_24hr_stats('ETH-BTC') + + :returns: ApiResponse + + .. code:: python + + { + "time": 1602832092060, // time + "symbol": "BTC-USDT", // symbol + "buy": "11328.9", // bestAsk + "sell": "11329", // bestBid + "changeRate": "-0.0055", // 24h change rate + "changePrice": "-63.6", // 24h change price + "high": "11610", // 24h highest price + "low": "11200", // 24h lowest price + "vol": "2282.70993217", // 24h volume the aggregated trading volume in BTC + "volValue": "25984946.157790431", // 24h total, the trading volume in quote currency of last 24 hours + "last": "11328.9", // last price + "averagePrice": "11360.66065903", // 24h average transaction price yesterday + "takerFeeRate": "0.001", // Basic Taker Fee + "makerFeeRate": "0.001", // Basic Maker Fee + "takerCoefficient": "1", // Taker Fee Coefficient + "makerCoefficient": "1" // Maker Fee Coefficient + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('market/stats', False, data=dict(data, **params)) + + def get_markets(self): + """Get supported market list + + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-market-list + + .. code:: python + + markets = client.get_markets() + + :returns: ApiResponse + + .. code:: python + + { + "data": [ + "USDS", //SC has been changed to USDS + "BTC", + "KCS", + "ALTS", //ALTS market includes ETH, NEO, TRX + "NFT-ETF", + "FIAT", + "DeFi", + "NFT", + "Metaverse", + "Polkadot", + "ETF" + ], + "code": "200000" + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + return self._get('markets', False) + + def get_order_book(self, symbol, depth_20=False, **params): + """Get a list of bids and asks aggregated by price for a symbol. + + Returns up to 20 or 100 depth each side. Fastest Order book API + + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-part-order-book-aggregated- + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param depth_20: If to return only 20 depth + :type depth_20: bool + + .. code:: python + + orders = client.get_order_book('KCS-BTC') + + :returns: ApiResponse + + .. code:: python + + { + "sequence": "3262786978", + "time": 1550653727731, + "bids": [ + ["6500.12", "0.45054140"], + ["6500.11", "0.45054140"] + ], + "asks": [ + ["6500.16", "0.57753524"], + ["6500.15", "0.57753524"] + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + path = 'market/orderbook/level2_' + if depth_20: + path += '20' + else: + path += '100' + + return self._get(path, False, data=dict(data, **params)) + + def get_full_order_book(self, symbol, **params): + """Get a list of all bids and asks aggregated by price for a symbol. + + This call is generally used by professional traders because it uses more server resources and traffic, + and Kucoin has strict access frequency control. + + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-full-order-book-aggregated- + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + + .. code:: python + + orders = client.get_order_book('KCS-BTC') + + :returns: ApiResponse + + .. code:: python + + { + "sequence": "3262786978", + "bids": [ + ["6500.12", "0.45054140"], # [price size] + ["6500.11", "0.45054140"] + ], + "asks": [ + ["6500.16", "0.57753524"], + ["6500.15", "0.57753524"] + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('market/orderbook/level2', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def get_trade_histories(self, symbol, **params): + """List the latest trades for a symbol + + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-trade-histories + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + + .. code:: python + + orders = client.get_trade_histories('KCS-BTC') + + :returns: ApiResponse + + .. code:: python + + [ + { + "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 + } + ] + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('market/histories', False, data=dict(data, **params)) + + def get_kline_data(self, symbol, kline_type='5min', start=None, end=None, **params): + """Get kline data + + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-klines + + For each query, the system would return at most 1500 pieces of data. + To obtain more data, please page the data by time. + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param kline_type: type of symbol, type of candlestick patterns: 1min, 3min, 5min, 15min, 30min, 1hour, 2hour, + 4hour, 6hour, 8hour, 12hour, 1day, 1week + :type kline_type: string + :param start: Start time as unix timestamp (optional) default start of day in UTC + :type start: int + :param end: End time as unix timestamp (optional) default now in UTC + :type end: int + + .. code:: python + + klines = client.get_kline_data('KCS-BTC', '5min', 1507479171, 1510278278) + + :returns: ApiResponse + + .. code:: python + + [ + [ + "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" + ] + ] + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + if kline_type is not None: + data['type'] = kline_type + if start is not None: + data['startAt'] = start + if end is not None: + data['endAt'] = end + + return self._get('market/candles', False, data=dict(data, **params)) + + def get_fiat_prices(self, base=None, currencies=None, **params): + """Get fiat price for currency + + https://www.kucoin.com/docs/rest/spot-trading/market-data/get-fiat-price + + :param base: (optional) Fiat,eg.USD,EUR, default is USD. + :type base: string + :param currencies: (optional) Cryptocurrencies.For multiple cyrptocurrencies, please separate them with + comma one by one. default is all + :type currencies: string + + .. code:: python + + prices = client.get_fiat_prices() + + :returns: ApiResponse + + .. code:: python + + { + "BTC": "3911.28000000", + "ETH": "144.55492453", + "LTC": "48.45888179", + "KCS": "0.45546856" + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + + if base is not None: + data['base'] = base + if currencies is not None: + data['currencies'] = currencies + + return self._get('prices', False, data=dict(data, **params)) + # User Account Endpoints def get_accounts(self, currency=None, account_type=None, **params): @@ -5078,241 +5591,28 @@ def hf_margin_create_order(self, symbol, type, side, size=None, price=None, fund :type cancel_after: string :param post_only: (optional) Post only flag (for limit order only) :type post_only: bool - :param hidden: (optional) Hidden order flag (for limit order only) - :type hidden: bool - :param iceberg: (optional) Iceberg order flag (for limit order only) - :type iceberg: bool - :param visible_size: (optional) The maximum visible size of an iceberg order (for limit orders only) - :type visible_size: string - :param is_isolated: (optional) True for isolated margin, False for cross margin (default is False) - :type margin_model: bool - :param auto_borrow: (optional) auto borrow flag (default is False). - When Margin HFTrading Account has inefficient balance, - System autoborrows inefficient assets and opens positions - according to the lowest market interest rate. - :type auto_borrow: bool - :param auto_repay: (optional) auto repay flag (default is False). - AutoPay allows returning borrowed assets when you close a position. - System automatically triggers the repayment and the maximum repayment - amount equals to the filled-order amount. - - .. code:: python - - order = client.hf_margin_create_order('ETH-USDT', Client.ORDER_LIMIT, Client.SIDE_BUY, size=20, price=2000) - order = client.hf_margin_create_order('ETH-USDT', Client.ORDER_MARKET, Client.SIDE_BUY, funds=20) - - :returns: ApiResponse - - .. code:: python - - todo add the response example - - :raises: KucoinResponseException, KucoinAPIException, MarketOrderException, LimitOrderException, KucoinRequestException - - """ - - if not client_oid: - client_oid = flat_uuid() - - data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, - time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) - - if is_isolated: - data['isIsolated'] = is_isolated # todo check this parameter for margin_create_order - if auto_borrow: - data['autoBorrow'] = auto_borrow - if auto_repay: - data['autoRepay'] = auto_repay - - return self._post('hf/margin/order', True, api_version=self.API_VERSION3, data=dict(data, **params)) - - def hf_margin_create_test_order(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, - remark=None, time_in_force=None, cancel_after=None, post_only=None, hidden=None, - iceberg=None, visible_size=None, is_isolated=None, auto_borrow=None, auto_repay=None, **params): - """Create an hf margin test order - - https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/place-hf-order-test - - :param symbol: Name of symbol e.g. KCS-BTC - :type symbol: string - :param type: order type (limit or market) - :type type: string - :param side: buy or sell - :type side: string - :param size: (optional) Desired amount in base currency (required for limit order) - :type size: string - :param price: (optional) Price (required for limit order) - :type price: string - :param funds: (optional) Desired amount of quote currency to use (for market order only) - :type funds: string - :param client_oid: (optional) Unique order id (default flat_uuid()) - :type client_oid: string - :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) - :type stp: string - :param remark: (optional) remark for the order, max 100 utf8 characters - :type remark: string - :param time_in_force: (optional) GTC, GTT, IOC, or FOK - default is GTC (for limit order only) - :type time_in_force: string - :param cancel_after: (optional) time in ms to cancel after (for limit order only) - :type cancel_after: string - :param post_only: (optional) Post only flag (for limit order only) - :type post_only: bool - :param hidden: (optional) Hidden order flag (for limit order only) - :type hidden: bool - :param iceberg: (optional) Iceberg order flag (for limit order only) - :type iceberg: bool - :param visible_size: (optional) The maximum visible size of an iceberg order (for limit orders only) - :type visible_size: string - :param is_isolated: (optional) True for isolated margin, False for cross margin (default is False) - :type margin_model: bool - :param auto_borrow: (optional) auto borrow flag (default is False). - When Margin HFTrading Account has inefficient balance, - System autoborrows inefficient assets and opens positions - according to the lowest market interest rate. - :type auto_borrow: bool - :param auto_repay: (optional) auto repay flag (default is False). - AutoPay allows returning borrowed assets when you close a position. - System automatically triggers the repayment and the maximum repayment - amount equals to the filled-order amount. - - .. code:: python - - order = client.hf_margin_create_test_order('ETH-USDT', Client.ORDER_LIMIT, Client.SIDE_BUY, size=20, price=2000) - order = client.hf_margin_create_test_order('ETH-USDT', Client.ORDER_MARKET, Client.SIDE_BUY, funds=20) - - :returns: ApiResponse - - .. code:: python - - todo add the response example - - :raises: KucoinResponseException, KucoinAPIException, MarketOrderException, LimitOrderException, KucoinRequestException - - """ - - if not client_oid: - client_oid = flat_uuid() - - data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, - time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) - - if is_isolated: - data['isIsolated'] = is_isolated # todo check this parameter for margin_create_order - if auto_borrow: - data['autoBorrow'] = auto_borrow - if auto_repay: - data['autoRepay'] = auto_repay - - return self._post('hf/margin/order/test', True, api_version=self.API_VERSION3, data=dict(data, **params)) - - def hf_margin_cancel_order(self, order_id, symbol, **params): - """Cancel an hf margin order by the orderId - - https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/cancel-hf-order-by-orderid - - :param order_id: OrderId - :type order_id: string - :param symbol: Name of symbol e.g. KCS-BTC - :type symbol: string - - .. code:: python - - res = client.hf_margin_cancel_order('5bd6e9286d99522a52e458de', 'KCS-BTC') - - :returns: ApiResponse - - .. code:: python - - todo add the response example - - :raises: KucoinResponseException, KucoinAPIException - - KucoinAPIException If order_id is not found - - """ - - data = { - 'symbol': symbol - } - - return self._delete('hf/margin/orders/{}'.format(order_id), True, api_version=self.API_VERSION3, data=dict(data, **params)) - - def hf_margin_cancel_order_by_client_oid(self, client_oid, symbol, **params): - """Cancel a hf margin order by the clientOid - - https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/cancel-hf-order-by-clientoid - - :param client_oid: ClientOid - :type client_oid: string - :param symbol: Name of symbol e.g. KCS-BTC - :type symbol: string - - .. code:: python - - res = client.hf_margin_cancel_order_by_client_oid('6d539dc614db3', 'KCS-BTC') - - :returns: ApiResponse - - .. code:: python - - todo add the response example - - :raises: KucoinResponseException, KucoinAPIException - - KucoinAPIException If order_id is not found - - """ - - data = { - 'symbol': symbol - } - - return self._delete('hf/margin/orders/client-order/{}'.format(client_oid), True, api_version=self.API_VERSION3, data=dict(data, **params)) - - def hf_margin_cancel_orders_by_symbol(self, symbol, trade_type, **params): - """Cancel all hf margin orders by symbol - - https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/cancel-all-hf-orders-by-symbol - - :param symbol: Name of symbol e.g. ETH-USDT - :type symbol: string - :param trade_type: MARGIN_TRADE (Margin Trading) or MARGIN_ISOLATED_TRADE (Isolated Margin Trading) - :type trade_type: string - - .. code:: python - - res = client.hf_margin_cancel_orders_by_symbol('ETH-USDT') - - :returns: ApiResponse - - .. code:: python - - todo add the response example - - :raises: KucoinResponseException, KucoinAPIException - - """ - - data = { - 'symbol': symbol, - 'tradeType': trade_type - } - - return self._delete('hf/margin/orders', True, api_version=self.API_VERSION3, data=dict(data, **params)) - - def hf_margin_get_active_orders(self, symbol, trade_type, **params): - """Get a list of active hf margin orders - - https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-active-hf-orders-list - - :param symbol: Name of symbol e.g. KCS-BTC - :type symbol: string - :param trade_type: MARGIN_TRADE (Margin Trading) or MARGIN_ISOLATED_TRADE (Isolated Margin Trading) - :type trade_type: string + :param hidden: (optional) Hidden order flag (for limit order only) + :type hidden: bool + :param iceberg: (optional) Iceberg order flag (for limit order only) + :type iceberg: bool + :param visible_size: (optional) The maximum visible size of an iceberg order (for limit orders only) + :type visible_size: string + :param is_isolated: (optional) True for isolated margin, False for cross margin (default is False) + :type margin_model: bool + :param auto_borrow: (optional) auto borrow flag (default is False). + When Margin HFTrading Account has inefficient balance, + System autoborrows inefficient assets and opens positions + according to the lowest market interest rate. + :type auto_borrow: bool + :param auto_repay: (optional) auto repay flag (default is False). + AutoPay allows returning borrowed assets when you close a position. + System automatically triggers the repayment and the maximum repayment + amount equals to the filled-order amount. .. code:: python - orders = client.hf_margin_get_active_orders('ETH-USDT') + order = client.hf_margin_create_order('ETH-USDT', Client.ORDER_LIMIT, Client.SIDE_BUY, size=20, price=2000) + order = client.hf_margin_create_order('ETH-USDT', Client.ORDER_MARKET, Client.SIDE_BUY, funds=20) :returns: ApiResponse @@ -5320,42 +5620,78 @@ def hf_margin_get_active_orders(self, symbol, trade_type, **params): todo add the response example - :raises: KucoinResponseException, KucoinAPIException + :raises: KucoinResponseException, KucoinAPIException, MarketOrderException, LimitOrderException, KucoinRequestException """ - data = { - 'symbol': symbol, - 'tradeType': trade_type - } + if not client_oid: + client_oid = flat_uuid() - return self._get('hf/margin/orders/active', True, api_version=self.API_VERSION3, data=dict(data, **params)) + data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, + time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) - def hf_margin_get_completed_orders(self, symbol, trade_type, side=None, type=None, start=None, end=None, last_id=None, limit=None, **params): - """Get a list of completed hf margin orders + if is_isolated: + data['isIsolated'] = is_isolated # todo check this parameter for margin_create_order + if auto_borrow: + data['autoBorrow'] = auto_borrow + if auto_repay: + data['autoRepay'] = auto_repay - https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-hf-filled-list + return self._post('hf/margin/order', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def hf_margin_create_test_order(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, + remark=None, time_in_force=None, cancel_after=None, post_only=None, hidden=None, + iceberg=None, visible_size=None, is_isolated=None, auto_borrow=None, auto_repay=None, **params): + """Create an hf margin test order + + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/place-hf-order-test :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string - :param trade_type: MARGIN_TRADE (Margin Trading) or MARGIN_ISOLATED_TRADE (Isolated Margin Trading) - :type trade_type: string - :param side: (optional) buy or sell - :type side: string - :param type: (optional) limit, market, limit_stop or market_stop + :param type: order type (limit or market) :type type: string - :param start: (optional) Start time as unix timestamp - :type start: int - :param end: (optional) End time as unix timestamp - :type end: int - :param last_id: (optional) The last orderId of the last page - :type last_id: int - :param limit: (optional) Number of orders - :type limit: int + :param side: buy or sell + :type side: string + :param size: (optional) Desired amount in base currency (required for limit order) + :type size: string + :param price: (optional) Price (required for limit order) + :type price: string + :param funds: (optional) Desired amount of quote currency to use (for market order only) + :type funds: string + :param client_oid: (optional) Unique order id (default flat_uuid()) + :type client_oid: string + :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) + :type stp: string + :param remark: (optional) remark for the order, max 100 utf8 characters + :type remark: string + :param time_in_force: (optional) GTC, GTT, IOC, or FOK - default is GTC (for limit order only) + :type time_in_force: string + :param cancel_after: (optional) time in ms to cancel after (for limit order only) + :type cancel_after: string + :param post_only: (optional) Post only flag (for limit order only) + :type post_only: bool + :param hidden: (optional) Hidden order flag (for limit order only) + :type hidden: bool + :param iceberg: (optional) Iceberg order flag (for limit order only) + :type iceberg: bool + :param visible_size: (optional) The maximum visible size of an iceberg order (for limit orders only) + :type visible_size: string + :param is_isolated: (optional) True for isolated margin, False for cross margin (default is False) + :type margin_model: bool + :param auto_borrow: (optional) auto borrow flag (default is False). + When Margin HFTrading Account has inefficient balance, + System autoborrows inefficient assets and opens positions + according to the lowest market interest rate. + :type auto_borrow: bool + :param auto_repay: (optional) auto repay flag (default is False). + AutoPay allows returning borrowed assets when you close a position. + System automatically triggers the repayment and the maximum repayment + amount equals to the filled-order amount. .. code:: python - orders = client.hf_margin_get_completed_orders('ETH-USDT', 'MARGIN_ISOLATED_TRADE') + order = client.hf_margin_create_test_order('ETH-USDT', Client.ORDER_LIMIT, Client.SIDE_BUY, size=20, price=2000) + order = client.hf_margin_create_test_order('ETH-USDT', Client.ORDER_MARKET, Client.SIDE_BUY, funds=20) :returns: ApiResponse @@ -5363,34 +5699,29 @@ def hf_margin_get_completed_orders(self, symbol, trade_type, side=None, type=Non todo add the response example - :raises: KucoinResponseException, KucoinAPIException + :raises: KucoinResponseException, KucoinAPIException, MarketOrderException, LimitOrderException, KucoinRequestException """ - data = { - 'symbol': symbol, - 'tradeType': trade_type - } + if not client_oid: + client_oid = flat_uuid() - if side: - data['side'] = side - if type: - data['type'] = type - if start: - data['startAt'] = start - if end: - data['endAt'] = end - if last_id: - data['lastId'] = last_id - if limit: - data['limit'] = limit + data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, + time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) - return self._get('hf/margin/orders/done', True, api_version=self.API_VERSION3, data=dict(data, **params)) + if is_isolated: + data['isIsolated'] = is_isolated # todo check this parameter for margin_create_order + if auto_borrow: + data['autoBorrow'] = auto_borrow + if auto_repay: + data['autoRepay'] = auto_repay - def hf_margin_get_order(self, order_id, symbol, **params): - """Get an hf margin order details by the orderId + return self._post('hf/margin/order/test', True, api_version=self.API_VERSION3, data=dict(data, **params)) - https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-hf-order-details-by-orderid + def hf_margin_cancel_order(self, order_id, symbol, **params): + """Cancel an hf margin order by the orderId + + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/cancel-hf-order-by-orderid :param order_id: OrderId :type order_id: string @@ -5399,7 +5730,7 @@ def hf_margin_get_order(self, order_id, symbol, **params): .. code:: python - order = client.hf_get_order('5bd6e9286d99522a52e458de', 'KCS-BTC') + res = client.hf_margin_cancel_order('5bd6e9286d99522a52e458de', 'KCS-BTC') :returns: ApiResponse @@ -5409,27 +5740,29 @@ def hf_margin_get_order(self, order_id, symbol, **params): :raises: KucoinResponseException, KucoinAPIException + KucoinAPIException If order_id is not found + """ data = { 'symbol': symbol } - return self._get('hf/margin/orders/{}'.format(order_id), True, api_version=self.API_VERSION3, data=dict(data, **params)) + return self._delete('hf/margin/orders/{}'.format(order_id), True, api_version=self.API_VERSION3, data=dict(data, **params)) - def hf_get_order_by_client_oid(self, client_oid, symbol, **params): - """Get hf margin order details by clientOid + def hf_margin_cancel_order_by_client_oid(self, client_oid, symbol, **params): + """Cancel a hf margin order by the clientOid - https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-hf-order-details-by-clientoid + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/cancel-hf-order-by-clientoid - :param client_oid: clientOid value - :type client_oid: str + :param client_oid: ClientOid + :type client_oid: string :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string .. code:: python - order = client.hf_get_order_by_client_oid('6d539dc614db312', 'KCS-BTC') + res = client.hf_margin_cancel_order_by_client_oid('6d539dc614db3', 'KCS-BTC') :returns: ApiResponse @@ -5439,190 +5772,87 @@ def hf_get_order_by_client_oid(self, client_oid, symbol, **params): :raises: KucoinResponseException, KucoinAPIException - """ - - data = { - 'symbol': symbol - } - - return self._get('hf/margin/orders/client-order/{}'.format(client_oid), True, api_version=self.API_VERSION3, data=dict(data, **params)) - - def hf_margin_get_symbol_with_active_orders(self, trade_type, **params): - """Get a list of symbols with active hf margin orders - - https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-active-hf-order-symbols - - :param trade_type: MARGIN_TRADE (Margin Trading) or MARGIN_ISOLATED_TRADE (Isolated Margin Trading) - :type trade_type: string - - .. code:: python - - orders = client.hf_margin_get_symbol_with_active_orders('MARGIN_TRADE') - - :returns: ApiResponse - - .. code:: python - - { - "code": "200000", - "data": { - "symbolSize": 1, - "symbols": ["ADA-USDT"] - } - } - - :raises: KucoinResponseException, KucoinAPIException + KucoinAPIException If order_id is not found """ data = { - 'tradeType': trade_type + 'symbol': symbol } - return self._get('hf/margin/order/active/symbols', True, api_version=self.API_VERSION3, data=dict(data, **params)) - - # Fill Endpoints - - def get_fills(self, trade_type, order_id=None, symbol=None, side=None, type=None, start=None, end=None, page=None, limit=None, **params): - """Get a list of recent fills. - - https://www.kucoin.com/docs/rest/spot-trading/fills/get-filled-list - - :param trade_type: TRADE (Spot Trading), MARGIN_TRADE (Margin Trading), MARGIN_ISOLATED_TRADE (Isolated Margin Trading), TRADE as default. - :type trade_type: string - :param order_id: (optional) OrderId - :type order_id: string - :param symbol: (optional) Name of symbol e.g. KCS-BTC - :type symbol: string - :param side: (optional) buy or sell - :type side: string - :param type: (optional) limit, market, limit_stop or market_stop - :type type: string - :param start: (optional) Start time as unix timestamp - :type start: int - :param end: (optional) End time as unix timestamp - :type end: int - :param page: (optional) Page number - :type page: int - :param limit: (optional) Number of orders - :type limit: int - - .. code:: python - - fills = client.get_fills('TRADE') - - :returns: ApiResponse - - .. code:: python - - { - "currentPage": 1, - "pageSize": 1, - "totalNum": 251915, - "totalPage": 251915, - "items": [ - { - "symbol": "BTC-USDT", - "tradeId": "5c35c02709e4f67d5266954e", - "orderId": "5c35c02703aa673ceec2a168", - "counterOrderId": "5c1ab46003aa676e487fa8e3", - "side": "buy", - "liquidity": "taker", - "forceTaker": true, - "price": "0.083", - "size": "0.8424304", - "funds": "0.0699217232", - "fee": "0", - "feeRate": "0", - "feeCurrency": "USDT", - "stop": "", - "type": "limit", - "createdAt": 1547026472000, - "tradeType": "TRADE" - } - ] - } + return self._delete('hf/margin/orders/client-order/{}'.format(client_oid), True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def hf_margin_cancel_orders_by_symbol(self, symbol, trade_type, **params): + """Cancel all hf margin orders by symbol + + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/cancel-all-hf-orders-by-symbol + + :param symbol: Name of symbol e.g. ETH-USDT + :type symbol: string + :param trade_type: MARGIN_TRADE (Margin Trading) or MARGIN_ISOLATED_TRADE (Isolated Margin Trading) + :type trade_type: string + + .. code:: python + + res = client.hf_margin_cancel_orders_by_symbol('ETH-USDT') + + :returns: ApiResponse + + .. code:: python + + todo add the response example :raises: KucoinResponseException, KucoinAPIException """ data = { + 'symbol': symbol, 'tradeType': trade_type } - if order_id: - data['orderId'] = order_id - if symbol: - data['symbol'] = symbol - if side: - data['side'] = side - if type: - data['type'] = type - if start: - data['startAt'] = start - if end: - data['endAt'] = end - if page: - data['currentPage'] = page - if limit: - data['pageSize'] = limit + return self._delete('hf/margin/orders', True, api_version=self.API_VERSION3, data=dict(data, **params)) - return self._get('fills', False, data=dict(data, **params)) + def hf_margin_get_active_orders(self, symbol, trade_type, **params): + """Get a list of active hf margin orders - def get_recent_fills(self, **params): - """Get a list of recent fills. + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-active-hf-orders-list - https://www.kucoin.com/docs/rest/spot-trading/fills/get-recent-filled-list + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param trade_type: MARGIN_TRADE (Margin Trading) or MARGIN_ISOLATED_TRADE (Isolated Margin Trading) + :type trade_type: string .. code:: python - fills = client.get_recent_fills() + orders = client.hf_margin_get_active_orders('ETH-USDT') :returns: ApiResponse .. code:: python - { - "code": "200000", - "data": [ - { - "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" - } - ] - } + todo add the response example :raises: KucoinResponseException, KucoinAPIException """ - return self._get('limit/fills', True, data=params) + data = { + 'symbol': symbol, + 'tradeType': trade_type + } - def hf_get_fills(self, symbol, order_id=None, side=None, type=None, start=None, end=None, last_id=None, limit=None, **params): - """Get a list of hf fills + return self._get('hf/margin/orders/active', True, api_version=self.API_VERSION3, data=dict(data, **params)) - https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/get-hf-filled-list + def hf_margin_get_completed_orders(self, symbol, trade_type, side=None, type=None, start=None, end=None, last_id=None, limit=None, **params): + """Get a list of completed hf margin orders + + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-hf-filled-list :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string - :param order_id: (optional) OrderId - :type order_id: string + :param trade_type: MARGIN_TRADE (Margin Trading) or MARGIN_ISOLATED_TRADE (Isolated Margin Trading) + :type trade_type: string :param side: (optional) buy or sell :type side: string :param type: (optional) limit, market, limit_stop or market_stop @@ -5638,51 +5868,23 @@ def hf_get_fills(self, symbol, order_id=None, side=None, type=None, start=None, .. code:: python - fills = client.hf_get_fills('ETH-USDT') + orders = client.hf_margin_get_completed_orders('ETH-USDT', 'MARGIN_ISOLATED_TRADE') :returns: ApiResponse .. code:: python - { - "code": "200000", - "data": { - "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 - } - } + todo add the response example :raises: KucoinResponseException, KucoinAPIException """ data = { - 'symbol': symbol + 'symbol': symbol, + 'tradeType': trade_type } - if order_id: - data['orderId'] = order_id if side: data['side'] = side if type: @@ -5696,35 +5898,21 @@ def hf_get_fills(self, symbol, order_id=None, side=None, type=None, start=None, if limit: data['limit'] = limit - return self._get('hf/fills', True, data=dict(data, **params)) + return self._get('hf/margin/orders/done', True, api_version=self.API_VERSION3, data=dict(data, **params)) - def hf_margin_get_fills(self, symbol, trade_type, order_id=None, side=None, type=None, start=None, end=None, last_id=None, limit=None, **params): - """Get a list of hf fills + def hf_margin_get_order(self, order_id, symbol, **params): + """Get an hf margin order details by the orderId - https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-hf-transaction-records + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-hf-order-details-by-orderid + :param order_id: OrderId + :type order_id: string :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string - :param trade_type: MARGIN_TRADE (Margin Trading) or MARGIN_ISOLATED_TRADE (Isolated Margin Trading) - :type trade_type: string - :param order_id: (optional) OrderId - :type order_id: string - :param side: (optional) buy or sell - :type side: string - :param type: (optional) limit, market, limit_stop or market_stop - :type type: string - :param start: (optional) Start time as unix timestamp - :type start: int - :param end: (optional) End time as unix timestamp - :type end: int - :param last_id: (optional) The last orderId of the last page - :type last_id: int - :param limit: (optional) Number of orders - :type limit: int .. code:: python - fills = client.hf_get_fills('ETH-USDT') + order = client.hf_get_order('5bd6e9286d99522a52e458de', 'KCS-BTC') :returns: ApiResponse @@ -5737,216 +5925,198 @@ def hf_margin_get_fills(self, symbol, trade_type, order_id=None, side=None, type """ data = { - 'symbol': symbol, - 'tradeType': trade_type + 'symbol': symbol } - if order_id: - data['orderId'] = order_id - if side: - data['side'] = side - if type: - data['type'] = type - if start: - data['startAt'] = start - if end: - data['endAt'] = end - if last_id: - data['lastId'] = last_id - if limit: - data['limit'] = limit - - return self._get('hf/margin/fills', True, api_version=self.API_VERSION3, data=dict(data, **params)) - - # Market Endpoints + return self._get('hf/margin/orders/{}'.format(order_id), True, api_version=self.API_VERSION3, data=dict(data, **params)) - def get_symbols(self, market=None, **params): - """Get a list of available currency pairs for trading. + def hf_get_order_by_client_oid(self, client_oid, symbol, **params): + """Get hf margin order details by clientOid - https://www.kucoin.com/docs/rest/spot-trading/market-data/get-symbols-list + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-hf-order-details-by-clientoid - :param market: (optional) Name of market e.g. BTC - :type market: string + :param client_oid: clientOid value + :type client_oid: str + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string .. code:: python - symbols = client.get_symbols() - symbols = client.get_symbols('USDS') + order = client.hf_get_order_by_client_oid('6d539dc614db312', 'KCS-BTC') :returns: ApiResponse .. code:: python - [ - { - "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 - }, - { - "symbol": "VET-USDT", - "name": "VET-USDT", - "baseCurrency": "VET", - "quoteCurrency": "USDT", - "feeCurrency": "USDT", - "market": "USDS", - "baseMinSize": "10", - "quoteMinSize": "0.01", - "baseMaxSize": "10000000000", - "quoteMaxSize": "99999999", - "baseIncrement": "0.0001", - "quoteIncrement": "0.000001", - "priceIncrement": "0.0000001", - "priceLimitRate": "0.1", - "minFunds": "0.1", - "isMarginEnabled": true, - "enableTrading": true - } - ] + todo add the response example :raises: KucoinResponseException, KucoinAPIException """ - data = {} - if market: - data['market'] = market + data = { + 'symbol': symbol + } - return self._get('symbols', False, api_version=self.API_VERSION2, data=dict(data, **params)) + return self._get('hf/margin/orders/client-order/{}'.format(client_oid), True, api_version=self.API_VERSION3, data=dict(data, **params)) - def get_symbol(self, symbol=None, **params): - """Get a symbol details for trading. + def hf_margin_get_symbol_with_active_orders(self, trade_type, **params): + """Get a list of symbols with active hf margin orders - https://www.kucoin.com/docs/rest/spot-trading/market-data/get-symbol-detail + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-active-hf-order-symbols - :param symbol: (optional) Name of symbol e.g. KCS-BTC - :type symbol: string + :param trade_type: MARGIN_TRADE (Margin Trading) or MARGIN_ISOLATED_TRADE (Isolated Margin Trading) + :type trade_type: string .. code:: python - symbol = client.get_symbol('XLM-USDT') + orders = client.hf_margin_get_symbol_with_active_orders('MARGIN_TRADE') :returns: ApiResponse .. code:: python { - "data" : { - "quoteMinSize" : "0.1", - "quoteCurrency" : "USDT", - "feeCurrency" : "USDT", - "symbol" : "BTC-USDT", - "market" : "USDS", - "baseMaxSize" : "10000000000", - "baseIncrement" : "0.00000001", - "quoteIncrement" : "0.000001", - "priceIncrement" : "0.1", - "priceLimitRate" : "0.1", - "minFunds" : "0.1", - "isMarginEnabled" : true, - "enableTrading" : true, - "baseCurrency" : "BTC", - "baseMinSize" : "0.00001", - "name" : "BTC-USDT", - "quoteMaxSize" : "99999999" - }, - "code" : "200000" + "code": "200000", + "data": { + "symbolSize": 1, + "symbols": ["ADA-USDT"] + } } :raises: KucoinResponseException, KucoinAPIException """ - data = {} - if symbol: - data['symbol'] = symbol + data = { + 'tradeType': trade_type + } - return self._get('symbol', False, api_version=self.API_VERSION2, data=dict(data, **params)) + return self._get('hf/margin/order/active/symbols', True, api_version=self.API_VERSION3, data=dict(data, **params)) - def get_ticker(self, symbol, **params): - """Get symbol ticker + # Fill Endpoints - https://www.kucoin.com/docs/rest/spot-trading/market-data/get-ticker + def get_fills(self, trade_type, order_id=None, symbol=None, side=None, type=None, start=None, end=None, page=None, limit=None, **params): + """Get a list of recent fills. - :param symbol: Name of symbol e.g. KCS-BTC + https://www.kucoin.com/docs/rest/spot-trading/fills/get-filled-list + + :param trade_type: TRADE (Spot Trading), MARGIN_TRADE (Margin Trading), MARGIN_ISOLATED_TRADE (Isolated Margin Trading), TRADE as default. + :type trade_type: string + :param order_id: (optional) OrderId + :type order_id: string + :param symbol: (optional) Name of symbol e.g. KCS-BTC :type symbol: string + :param side: (optional) buy or sell + :type side: string + :param type: (optional) limit, market, limit_stop or market_stop + :type type: string + :param start: (optional) Start time as unix timestamp + :type start: int + :param end: (optional) End time as unix timestamp + :type end: int + :param page: (optional) Page number + :type page: int + :param limit: (optional) Number of orders + :type limit: int .. code:: python - ticker = client.get_ticker('ETH-BTC') + fills = client.get_fills('TRADE') :returns: ApiResponse .. code:: python { - "sequence": "1550467636704", - "price": "0.03715005", - "size": "0.17", - "bestAsk": "0.03715004", - "bestAskSize": "1.788", - "bestBid": "0.03710768", - "bestBidSize": "3.803", - "time": 1550653727731 + "currentPage": 1, + "pageSize": 1, + "totalNum": 251915, + "totalPage": 251915, + "items": [ + { + "symbol": "BTC-USDT", + "tradeId": "5c35c02709e4f67d5266954e", + "orderId": "5c35c02703aa673ceec2a168", + "counterOrderId": "5c1ab46003aa676e487fa8e3", + "side": "buy", + "liquidity": "taker", + "forceTaker": true, + "price": "0.083", + "size": "0.8424304", + "funds": "0.0699217232", + "fee": "0", + "feeRate": "0", + "feeCurrency": "USDT", + "stop": "", + "type": "limit", + "createdAt": 1547026472000, + "tradeType": "TRADE" + } + ] } :raises: KucoinResponseException, KucoinAPIException """ + data = { - 'symbol': symbol + 'tradeType': trade_type } - return self._get('market/orderbook/level1', False, data=dict(data, **params)) - def get_tickers(self): - """Get symbol tickers + if order_id: + data['orderId'] = order_id + if symbol: + data['symbol'] = symbol + if side: + data['side'] = side + if type: + data['type'] = type + if start: + data['startAt'] = start + if end: + data['endAt'] = end + if page: + data['currentPage'] = page + if limit: + data['pageSize'] = limit - https://www.kucoin.com/docs/rest/spot-trading/market-data/get-all-tickers + return self._get('fills', False, data=dict(data, **params)) + + def get_recent_fills(self, **params): + """Get a list of recent fills. + + https://www.kucoin.com/docs/rest/spot-trading/fills/get-recent-filled-list .. code:: python - tickers = client.get_tickers() + fills = client.get_recent_fills() :returns: ApiResponse .. code:: python { - "time": 1602832092060, - "ticker": [ + "code": "200000", + "data": [ { - "symbol": "BTC-USDT", // symbol - "symbolName": "BTC-USDT", // Name of trading pairs, it would change after renaming - "buy": "11328.9", // bestAsk - "sell": "11329", // bestBid - "bestBidSize": "0.1", - "bestAskSize": "1", - "changeRate": "-0.0055", // 24h change rate - "changePrice": "-63.6", // 24h change price - "high": "11610", // 24h highest price - "low": "11200", // 24h lowest price - "vol": "2282.70993217", // 24h volume,the aggregated trading volume in BTC - "volValue": "25984946.157790431", // 24h total, the trading volume in quote currency of last 24 hours - "last": "11328.9", // last price - "averagePrice": "11360.66065903", // 24h average transaction price yesterday - "takerFeeRate": "0.001", // Basic Taker Fee - "makerFeeRate": "0.001", // Basic Maker Fee - "takerCoefficient": "1", // Taker Fee Coefficient - "makerCoefficient": "1" // Maker Fee Coefficient + "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" } ] } @@ -5954,41 +6124,66 @@ def get_tickers(self): :raises: KucoinResponseException, KucoinAPIException """ - return self._get('market/allTickers', False) - def get_24hr_stats(self, symbol, **params): - """Get 24hr stats for a symbol. Volume is in base currency units. open, high, low are in quote currency units. + return self._get('limit/fills', True, data=params) - https://www.kucoin.com/docs/rest/spot-trading/market-data/get-24hr-stats + def hf_get_fills(self, symbol, order_id=None, side=None, type=None, start=None, end=None, last_id=None, limit=None, **params): + """Get a list of hf fills + + https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/get-hf-filled-list :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string + :param order_id: (optional) OrderId + :type order_id: string + :param side: (optional) buy or sell + :type side: string + :param type: (optional) limit, market, limit_stop or market_stop + :type type: string + :param start: (optional) Start time as unix timestamp + :type start: int + :param end: (optional) End time as unix timestamp + :type end: int + :param last_id: (optional) The last orderId of the last page + :type last_id: int + :param limit: (optional) Number of orders + :type limit: int .. code:: python - stats = client.get_24hr_stats('ETH-BTC') + fills = client.hf_get_fills('ETH-USDT') :returns: ApiResponse .. code:: python { - "time": 1602832092060, // time - "symbol": "BTC-USDT", // symbol - "buy": "11328.9", // bestAsk - "sell": "11329", // bestBid - "changeRate": "-0.0055", // 24h change rate - "changePrice": "-63.6", // 24h change price - "high": "11610", // 24h highest price - "low": "11200", // 24h lowest price - "vol": "2282.70993217", // 24h volume the aggregated trading volume in BTC - "volValue": "25984946.157790431", // 24h total, the trading volume in quote currency of last 24 hours - "last": "11328.9", // last price - "averagePrice": "11360.66065903", // 24h average transaction price yesterday - "takerFeeRate": "0.001", // Basic Taker Fee - "makerFeeRate": "0.001", // Basic Maker Fee - "takerCoefficient": "1", // Taker Fee Coefficient - "makerCoefficient": "1" // Maker Fee Coefficient + "code": "200000", + "data": { + "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 + } } :raises: KucoinResponseException, KucoinAPIException @@ -5999,73 +6194,115 @@ def get_24hr_stats(self, symbol, **params): 'symbol': symbol } - return self._get('market/stats', False, data=dict(data, **params)) + if order_id: + data['orderId'] = order_id + if side: + data['side'] = side + if type: + data['type'] = type + if start: + data['startAt'] = start + if end: + data['endAt'] = end + if last_id: + data['lastId'] = last_id + if limit: + data['limit'] = limit - def get_markets(self): - """Get supported market list + return self._get('hf/fills', True, data=dict(data, **params)) - https://www.kucoin.com/docs/rest/spot-trading/market-data/get-market-list + def hf_margin_get_fills(self, symbol, trade_type, order_id=None, side=None, type=None, start=None, end=None, last_id=None, limit=None, **params): + """Get a list of hf fills + + https://www.kucoin.com/docs/rest/margin-trading/margin-hf-trade/get-hf-transaction-records + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + :param trade_type: MARGIN_TRADE (Margin Trading) or MARGIN_ISOLATED_TRADE (Isolated Margin Trading) + :type trade_type: string + :param order_id: (optional) OrderId + :type order_id: string + :param side: (optional) buy or sell + :type side: string + :param type: (optional) limit, market, limit_stop or market_stop + :type type: string + :param start: (optional) Start time as unix timestamp + :type start: int + :param end: (optional) End time as unix timestamp + :type end: int + :param last_id: (optional) The last orderId of the last page + :type last_id: int + :param limit: (optional) Number of orders + :type limit: int .. code:: python - markets = client.get_markets() + fills = client.hf_get_fills('ETH-USDT') :returns: ApiResponse .. code:: python - { - "data": [ - "USDS", //SC has been changed to USDS - "BTC", - "KCS", - "ALTS", //ALTS market includes ETH, NEO, TRX - "NFT-ETF", - "FIAT", - "DeFi", - "NFT", - "Metaverse", - "Polkadot", - "ETF" - ], - "code": "200000" - } + todo add the response example :raises: KucoinResponseException, KucoinAPIException """ - return self._get('markets', False) - def get_order_book(self, symbol, depth_20=False, **params): - """Get a list of bids and asks aggregated by price for a symbol. + data = { + 'symbol': symbol, + 'tradeType': trade_type + } - Returns up to 20 or 100 depth each side. Fastest Order book API + if order_id: + data['orderId'] = order_id + if side: + data['side'] = side + if type: + data['type'] = type + if start: + data['startAt'] = start + if end: + data['endAt'] = end + if last_id: + data['lastId'] = last_id + if limit: + data['limit'] = limit - https://www.kucoin.com/docs/rest/spot-trading/market-data/get-part-order-book-aggregated- + return self._get('hf/margin/fills', True, api_version=self.API_VERSION3, data=dict(data, **params)) - :param symbol: Name of symbol e.g. KCS-BTC - :type symbol: string - :param depth_20: If to return only 20 depth - :type depth_20: bool + # Margin Info Endpoints + + def margin_get_leverage_token_info(self, currency=None, **params): + """Get a list of leverage token info + + https://www.kucoin.com/docs/rest/margin-trading/margin-info/get-leveraged-token-info + + :param currency: (optional) Currency, if empty query all currencies + :type currency: string .. code:: python - orders = client.get_order_book('KCS-BTC') + leverage_token_info = client.get_leverage_token_info() :returns: ApiResponse .. code:: python { - "sequence": "3262786978", - "time": 1550653727731, - "bids": [ - ["6500.12", "0.45054140"], - ["6500.11", "0.45054140"] - ], - "asks": [ - ["6500.16", "0.57753524"], - ["6500.15", "0.57753524"] + "success": true, + "code": "200", + "msg": "success", + "retry": false, + "data": [ + { + "currency": "BTCUP", + "netAsset": 0.001, + "targetLeverage": "2-4", + "actualLeverage": "2.33", + "assetsUnderManagement": "766834.764756714775 USDT" + "basket": "-78.671762 XBTUSDTM" + } ] } @@ -6073,45 +6310,39 @@ def get_order_book(self, symbol, depth_20=False, **params): """ - data = { - 'symbol': symbol - } - path = 'market/orderbook/level2_' - if depth_20: - path += '20' - else: - path += '100' - - return self._get(path, False, data=dict(data, **params)) + data = {} - def get_full_order_book(self, symbol, **params): - """Get a list of all bids and asks aggregated by price for a symbol. + if currency: + data['currency'] = currency - This call is generally used by professional traders because it uses more server resources and traffic, - and Kucoin has strict access frequency control. + return self._get('etf/info', True, api_version=self.API_VERSION3, data=dict(data, **params)) - https://www.kucoin.com/docs/rest/spot-trading/market-data/get-full-order-book-aggregated- + def margin_get_all_trading_pairs_mark_prices(self, **params): + """Get a list of trading pairs and their mark prices - :param symbol: Name of symbol e.g. KCS-BTC - :type symbol: string + https://www.kucoin.com/docs/rest/margin-trading/margin-info/get-all-trading-pairs-mark-price .. code:: python - orders = client.get_order_book('KCS-BTC') + trading_pairs_mark_prices = client.get_all_trading_pairs_mark_prices() :returns: ApiResponse .. code:: python { - "sequence": "3262786978", - "bids": [ - ["6500.12", "0.45054140"], # [price size] - ["6500.11", "0.45054140"] - ], - "asks": [ - ["6500.16", "0.57753524"], - ["6500.15", "0.57753524"] + "code": "200000", + "data": [ + { + "symbol": "POND-BTC", + "timePoint": 1721027167000, + "value": 2.96603125E-7 + }, + { + "symbol": "REN-BTC", + "timePoint": 1721027217000, + "value": 7.36068750E-7 + } ] } @@ -6119,157 +6350,162 @@ def get_full_order_book(self, symbol, **params): """ - data = { - 'symbol': symbol - } - - return self._get('market/orderbook/level2', True, api_version=self.API_VERSION3, data=dict(data, **params)) + return self._get('mark-price/all-symbols', False, api_version=self.API_VERSION3, data=params) - def get_trade_histories(self, symbol, **params): - """List the latest trades for a symbol + def margin_get_mark_price(self, symbol, **params): + """Get the mark price of a symbol - https://www.kucoin.com/docs/rest/spot-trading/market-data/get-trade-histories + https://www.kucoin.com/docs/rest/margin-trading/margin-info/get-mark-price :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string .. code:: python - orders = client.get_trade_histories('KCS-BTC') + mark_price = client.get_mark_price('ETH-USDT') :returns: ApiResponse .. code:: python - [ - { - "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 + { + "code": "200000", + "data": { + "symbol": "USDT-BTC", + "timePoint": 1659930234000, + "value": 0.0000429 } - ] + } :raises: KucoinResponseException, KucoinAPIException """ - data = { - 'symbol': symbol - } - - return self._get('market/histories', False, data=dict(data, **params)) - - def get_kline_data(self, symbol, kline_type='5min', start=None, end=None, **params): - """Get kline data + return self._get('mark-price/{}'.format(symbol)'/current', False, data=dict(data, **params)) - https://www.kucoin.com/docs/rest/spot-trading/market-data/get-klines - - For each query, the system would return at most 1500 pieces of data. - To obtain more data, please page the data by time. + def margin_get_config(self, **params): + """Get the margin configuration - :param symbol: Name of symbol e.g. KCS-BTC - :type symbol: string - :param kline_type: type of symbol, type of candlestick patterns: 1min, 3min, 5min, 15min, 30min, 1hour, 2hour, - 4hour, 6hour, 8hour, 12hour, 1day, 1week - :type kline_type: string - :param start: Start time as unix timestamp (optional) default start of day in UTC - :type start: int - :param end: End time as unix timestamp (optional) default now in UTC - :type end: int + https://www.kucoin.com/docs/rest/margin-trading/margin-info/get-margin-configuration-info .. code:: python - klines = client.get_kline_data('KCS-BTC', '5min', 1507479171, 1510278278) + margin_config = client.get_config() :returns: ApiResponse .. code:: python - [ - [ - "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" - ] - ] + { + "code": "200000", + "data": { + "currencyList": [ + "XEM", + "MATIC", + "VRA", + ... + ], + "maxLeverage": 5, + "warningDebtRatio": "0.95", + "liqDebtRatio": "0.97" + } + } :raises: KucoinResponseException, KucoinAPIException """ - data = { - 'symbol': symbol - } - - if kline_type is not None: - data['type'] = kline_type - if start is not None: - data['startAt'] = start - if end is not None: - data['endAt'] = end - - return self._get('market/candles', False, data=dict(data, **params)) + return self._get('margin/config', True, data=params) - def get_fiat_prices(self, base=None, currencies=None, **params): - """Get fiat price for currency + def margin_get_cross_isolated_risk_limit_config(self, isolated, symbol=None, currency=None, **params): + """Get the cross or isolated margin risk limit configuration - https://www.kucoin.com/docs/rest/spot-trading/market-data/get-fiat-price + https://www.kucoin.com/docs/rest/margin-trading/margin-info/get-cross-isolated-margin-risk-limit-currency-config - :param base: (optional) Fiat,eg.USD,EUR, default is USD. - :type base: string - :param currencies: (optional) Cryptocurrencies.For multiple cyrptocurrencies, please separate them with - comma one by one. default is all - :type currencies: string + :param isolated: True for isolated margin, False for cross margin + :type isolated: bool + :param symbol: (optional) Name of symbol e.g. KCS-BTC + :type symbol: string + :param currency: (optional) Currency + :type currency: string .. code:: python - prices = client.get_fiat_prices() + risk_limit_config = client.get_cross_isolated_risk_limit_config(False) :returns: ApiResponse .. code:: python + CROSS MARGIN RESPONSES { - "BTC": "3911.28000000", - "ETH": "144.55492453", - "LTC": "48.45888179", - "KCS": "0.45546856" + "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 + } + ] } :raises: KucoinResponseException, KucoinAPIException """ - data = {} + data = { + 'isolated': isolated + } - if base is not None: - data['base'] = base - if currencies is not None: - data['currencies'] = currencies + if symbol: + data['symbol'] = symbol + if currency: + data['currency'] = currency - return self._get('prices', False, data=dict(data, **params)) + return self._get('margin/currencies', True, api_version=self.API_VERSION3, data=dict(data, **params)) # Websocket Endpoints From 581d4f8c31c0d61548fe0106e57c0b981191a053 Mon Sep 17 00:00:00 2001 From: rayBastard Date: Sun, 17 Nov 2024 18:57:56 +0100 Subject: [PATCH 45/60] typo fixed --- kucoin/client.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/kucoin/client.py b/kucoin/client.py index 81f762a..a6b9178 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -6381,7 +6381,13 @@ def margin_get_mark_price(self, symbol, **params): """ - return self._get('mark-price/{}'.format(symbol)'/current', False, data=dict(data, **params)) + data = { + 'symbol': symbol + } + + return self._get('mark-price/{}/current'.format(symbol), False, data=dict(data, **params)) + + def margin_get_config(self, **params): """Get the margin configuration From f09786289465c2ce1e35c1f5db4b73de98fe9503 Mon Sep 17 00:00:00 2001 From: rayBastard Date: Sun, 17 Nov 2024 19:14:26 +0100 Subject: [PATCH 46/60] margin_get_isolated_synbols_config, margin_get_isolated_account_info, margin_get_single_isolated_account_info added --- kucoin/client.py | 191 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 190 insertions(+), 1 deletion(-) diff --git a/kucoin/client.py b/kucoin/client.py index a6b9178..7fc3e4d 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -1809,7 +1809,7 @@ def hf_get_account_activity(self, currency=None, direction=None, biz_type=None, path = 'hf/margin/account/ledgers' return self._get(path, True, data=dict(data, **params)) - def get_futures_account_activity(self, currency=None, type=None, start=None, end=None, limit=None, offset=None, forward=True, **params): + def futures_get_account_activity(self, currency=None, type=None, start=None, end=None, limit=None, offset=None, forward=True, **params): """Get list of futures account activity https://www.kucoin.com/docs/rest/account/basic-info/get-account-ledgers-futures @@ -6513,6 +6513,195 @@ def margin_get_cross_isolated_risk_limit_config(self, isolated, symbol=None, cur return self._get('margin/currencies', True, api_version=self.API_VERSION3, data=dict(data, **params)) + def margin_get_isolated_synbols_config(self, **params): + """Get the isolated margin symbol configuration + + https://www.kucoin.com/docs/rest/margin-trading/isolated-margin/get-isolated-margin-symbols-configuration + + .. code:: python + + isolated_symbols_config = client.get_isolated_synbols_config() + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": [ + { + "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 + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + return self._get('isolated/symbols', True, data=params) + + def margin_get_isolated_account_info(self, balance_currency=None, **params): + """Get the isolated margin account info + + https://www.kucoin.com/docs/rest/margin-trading/isolated-margin/get-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 balance_currency: string + + .. code:: python + + isolated_account_info = client.get_isolated_account_info() + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "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" + } + } + ] + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + + if balance_currency: + data['balanceCurrency'] = balance_currency + + return self._get('isolated/accounts', True, data=dict(data, **params)) + + def margin_get_single_isolated_account_info(self, symbol, **params): + """Get the isolated margin account info for a single symbol + + https://www.kucoin.com/docs/rest/margin-trading/isolated-margin/get-single-isolated-margin-account-info + + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + + .. code:: python + + isolated_account_info = client.get_single_isolated_account_info('EOS-USDC') + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "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" + } + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('isolated/account/{}'.format(symbol), True, data=dict(data, **params)) + # Websocket Endpoints def get_ws_endpoint(self, private=False): From 119a7e2b80d89949b187e3c9e2ea10e7619bbcf4 Mon Sep 17 00:00:00 2001 From: rayBastard Date: Sun, 17 Nov 2024 19:45:13 +0100 Subject: [PATCH 47/60] margin trading endpoints added margin_borrow margin_repay margin_get_borrow_history margin_get_repay_history margin_get_cross_isolated_interest_records margin_get_cross_trading_pairs_config margin_modify_leverage_multiplie --- kucoin/client.py | 418 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 418 insertions(+) diff --git a/kucoin/client.py b/kucoin/client.py index 7fc3e4d..0bfc155 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -6701,6 +6701,424 @@ def margin_get_single_isolated_account_info(self, symbol, **params): } return self._get('isolated/account/{}'.format(symbol), True, data=dict(data, **params)) + + def margin_borrow(self, currency, size, time_in_force, isolated=False, symbol=None, is_hf=False, **params): + """Borrow funds for margin trading + + https://www.kucoin.com/docs/rest/margin-trading/margin-trading-v3-/margin-borrowing + + :param currency: Currency + :type currency: string + :param size: Amount to borrow + :type size: string + :param time_in_force: GTC (Good till cancelled) or GTT (Good till time) + :type time_in_force: string + :param isolated: (optional) True for isolated margin, False for cross margin + :type isolated: bool + :param symbol: (optional) Name of symbol e.g. KCS-BTC + :type symbol: string + :param is_hf: (optional) true: high frequency borrowing, false: low frequency borrowing; default false + :type is_hf: bool + + .. code:: python + + borrow = client.margin_borrow('USDT', '100', 'GTC') + + :returns: ApiResponse + + .. code:: python + + { + "success": true, + "code": "200", + "msg": "success", + "retry": false, + "data": { + "orderNo": "5da6dba0f943c0c81f5d5db5", + "actualSize": 10 + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'currency': currency, + 'size': size, + 'timeInForce': time_in_force + } + + if isolated: + data['isolated'] = isolated + if symbol: + data['symbol'] = symbol + if is_hf: + data['isHf'] = is_hf + + return self._post('margin/borrow', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def margin_repay(self, currency, size, isolated=False, symbol=None, is_hf=False, **params): + """Repay borrowed funds for margin trading + + https://www.kucoin.com/docs/rest/margin-trading/margin-trading-v3-/repayment + + :param currency: Currency + :type currency: string + :param size: Amount to repay + :type size: string + :param isolated: (optional) True for isolated margin, False for cross margin + :type isolated: bool + :param symbol: (optional) Name of symbol e.g. KCS-BTC + :type symbol: string + :param is_hf: (optional) true: high frequency borrowing, false: low frequency borrowing; default false + :type is_hf: bool + + .. code:: python + + repay = client.margin_repay('USDT', '100') + + :returns: ApiResponse + + .. code:: python + + { + "success": true, + "code": "200", + "msg": "success", + "retry": false, + "data": { + "orderNo": "5da6dba0f943c0c81f5d5db5", + "actualSize": 10 + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'currency': currency, + 'size': size + } + + if isolated: + data['isolated'] = isolated + if symbol: + data['symbol'] = symbol + if is_hf: + data['isHf'] = is_hf + + return self._post('margin/repay', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def margin_get_borrow_history(self, currency, isolated=False, symbol=None, order_no=None, + start=None, end=None, page=None, limit=None, **params): + + """Get the borrow history for margin trading + + https://www.kucoin.com/docs/rest/margin-trading/margin-trading-v3-/get-margin-borrowing-history + + :param currency: Currency + :type currency: string + :param isolated: (optional) True for isolated margin, False for cross margin + :type isolated: bool + :param symbol: (optional) Name of symbol e.g. KCS-BTC + :type symbol: string + :param order_no: (optional) OrderNo + :type order_no: string + :param start: (optional) Start time as unix timestamp + :type start: int + :param end: (optional) End time as unix timestamp + :type end: int + :param page: (optional) Page number + :type page: int + :param limit: (optional) Number of orders + :type limit: int + + .. code:: python + + borrow_history = client.margin_get_borrow_history('USDT') + + :returns: ApiResponse + + .. code:: python + + { + "currentPage": 1, + "pageSize": 50, + "totalNum": 1, + "totalPage": 1, + "items": [ + { + "orderNo": "5da6dba0f943c0c81f5d5db5", + "symbol": "BTC-USDT", + "currency": "USDT", + "size": 10, + "actualSize": 10, + "status": "DONE", + "createdTime": 1555056425000 + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'currency': currency + } + + if isolated: + data['isolated'] = isolated + if symbol: + data['symbol'] = symbol + if order_no: + data['orderNo'] = order_no + if start: + data['startTime'] = start + if end: + data['endTime'] = end + if page: + data['currentPage'] = page + if limit: + data['pageSize'] = limit + + return self._get('margin/borrow', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def margin_get_repay_history(self, currency, isolated=False, symbol=None, order_no=None, + start=None, end=None, page=None, limit=None, **params): + + """Get the repay history for margin trading + + https://www.kucoin.com/docs/rest/margin-trading/margin-trading-v3-/get-repayment-history + + :param currency: Currency + :type currency: string + :param isolated: (optional) True for isolated margin, False for cross margin + :type isolated: bool + :param symbol: (optional) Name of symbol e.g. KCS-BTC + :type symbol: string + :param order_no: (optional) OrderNo + :type order_no: string + :param start: (optional) Start time as unix timestamp + :type start: int + :param end: (optional) End time as unix timestamp + :type end: int + :param page: (optional) Page number + :type page: int + :param limit: (optional) Number of orders + :type limit: int + + .. code:: python + + repay_history = client.margin_get_repay_history('USDT') + + :returns: ApiResponse + + .. code:: python + + { + "currentPage": 1, + "pageSize": 50, + "totalNum": 1, + "totalPage": 1, + "items": { + "orderNo": "5da6dba0f943c0c81f5d5db5", + "symbol": "BTC-USDT", + "currency": "USDT", + "size": 10, + "actualSize": 10, + "status": "DONE", + "createdTime": 1555056425000 + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'currency': currency + } + + if isolated: + data['isolated'] = isolated + if symbol: + data['symbol'] = symbol + if order_no: + data['orderNo'] = order_no + if start: + data['startTime'] = start + if end: + data['endTime'] = end + if page: + data['currentPage'] = page + if limit: + data['pageSize'] = limit + + return self._get('margin/repay', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def margin_get_cross_isolated_interest_records(self, isolated=False, symbol=None, currency=None, + start=None, end=None, page=None, limit=None, **params): + + """Get the cross or isolated margin interest records + + https://www.kucoin.com/docs/rest/margin-trading/margin-trading-v3-/get-cross-isolated-margin-interest-records + + :param isolated: (optional) True for isolated margin, False for cross margin + :type isolated: bool + :param symbol: (optional) Name of symbol e.g. KCS-BTC + :type symbol: string + :param currency: (optional) Currency + :type currency: string + :param start: (optional) Start time as unix timestamp + :type start: int + :param end: (optional) End time as unix timestamp + :type end: int + :param page: (optional) Page number + :type page: int + :param limit: (optional) Number of orders + :type limit: int + + .. code:: python + + interest_records = client.margin_get_cross_isolated_interest_records() + + :returns: ApiResponse + + .. code:: python + + { + "currentPage": 1, + "pageSize": 50, + "totalNum": 1, + "totalPage": 1, + "items": [ + { + "createdAt": 1697783812257, + "currency": "XMR", + "interestAmount": "0.1", + "dayRatio": "0.001" + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + + if isolated: + data['isolated'] = isolated + if symbol: + data['symbol'] = symbol + if currency: + data['currency'] = currency + if start: + data['startTime'] = start + if end: + data['endTime'] = end + if page: + data['currentPage'] = page + if limit: + data['pageSize'] = limit + + return self._get('margin/interest', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def margin_get_cross_trading_pairs_config(self, symbol=None, **params): + """Get the cross margin trading pairs configuration + + https://www.kucoin.com/docs/rest/margin-trading/margin-trading-v3-/get-cross-margin-trading-pairs-configuration + + :param symbol: (optional) Name of symbol e.g. KCS-BTC + :type symbol: string + + .. code:: python + + trading_pairs_config = client.margin_get_cross_trading_pairs_config() + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "timestamp": 1718779915377, + "items": [{ + "symbol": "ATOM-USDT", + "name": "ATOM-USDT", + "enableTrading": true, + "market": "USDS", + "baseCurrency": "ATOM", + "quoteCurrency": "USDT", + "baseIncrement": 0.0001, + "baseMinSize": 0.1, + "quoteIncrement": 0.0001, + "quoteMinSize": 0.1, + "baseMaxSize": 10000000000, + "quoteMaxSize": 99999999, + "priceIncrement": 0.0001, + "feeCurrency": "USDT", + "priceLimitRate": 0.1, + "minFunds": 0.1 + }] + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + + if symbol: + data['symbol'] = symbol + + return self._get('margin/symbols', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def margin_modify_leverage_multiplier(self, leverage, symbol=None, isolated=False, **params): + """Modify the leverage multiplier + + https://www.kucoin.com/docs/rest/margin-trading/margin-trading-v3-/modify-leverage-multiplier + + :param leverage: Must be greater than 1 and up to two decimal places, + and cannot be less than the user's current debt leverage or greater than the system's maximum leverage + :type leverage: int + :param symbol: (optional) Name of symbol e.g. KCS-BTC + :type symbol: string + :param isolated: (optional) True for isolated margin, False for cross margin + :type isolated: bool + + .. code:: python + + leverage_multiplier = client.margin_modify_leverage_multiplier(5) + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": None + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'leverage': leverage + } + + if symbol: + data['symbol'] = symbol + if isolated: + data['isolated'] = isolated + + return self._post('position/update-user-leverage', True, api_version=self.API_VERSION3, data=dict(data, **params)) # Websocket Endpoints From 061f96cdcc093e9b644020674d6c1c2ae52f9227 Mon Sep 17 00:00:00 2001 From: rayBastard Date: Sun, 17 Nov 2024 20:04:07 +0100 Subject: [PATCH 48/60] Lending Market Endpoints added margin_lending_get_currency_info margin_lending_get_interest_rate margin_lending_subscribtion margin_lending_redemption margin_lending_modify_subscription_orders margin_lending_get_redemtion_orders margin_lending_get_subscription_orders --- kucoin/client.py | 375 ++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 357 insertions(+), 18 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 0bfc155..450f248 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -6701,7 +6701,7 @@ def margin_get_single_isolated_account_info(self, symbol, **params): } return self._get('isolated/account/{}'.format(symbol), True, data=dict(data, **params)) - + def margin_borrow(self, currency, size, time_in_force, isolated=False, symbol=None, is_hf=False, **params): """Borrow funds for margin trading @@ -6757,7 +6757,7 @@ def margin_borrow(self, currency, size, time_in_force, isolated=False, symbol=No data['isHf'] = is_hf return self._post('margin/borrow', True, api_version=self.API_VERSION3, data=dict(data, **params)) - + def margin_repay(self, currency, size, isolated=False, symbol=None, is_hf=False, **params): """Repay borrowed funds for margin trading @@ -6810,10 +6810,10 @@ def margin_repay(self, currency, size, isolated=False, symbol=None, is_hf=False, data['isHf'] = is_hf return self._post('margin/repay', True, api_version=self.API_VERSION3, data=dict(data, **params)) - - def margin_get_borrow_history(self, currency, isolated=False, symbol=None, order_no=None, + + def margin_get_borrow_history(self, currency, isolated=False, symbol=None, order_no=None, start=None, end=None, page=None, limit=None, **params): - + """Get the borrow history for margin trading https://www.kucoin.com/docs/rest/margin-trading/margin-trading-v3-/get-margin-borrowing-history @@ -6836,7 +6836,7 @@ def margin_get_borrow_history(self, currency, isolated=False, symbol=None, order :type limit: int .. code:: python - + borrow_history = client.margin_get_borrow_history('USDT') :returns: ApiResponse @@ -6883,12 +6883,12 @@ def margin_get_borrow_history(self, currency, isolated=False, symbol=None, order data['currentPage'] = page if limit: data['pageSize'] = limit - + return self._get('margin/borrow', True, api_version=self.API_VERSION3, data=dict(data, **params)) - + def margin_get_repay_history(self, currency, isolated=False, symbol=None, order_no=None, start=None, end=None, page=None, limit=None, **params): - + """Get the repay history for margin trading https://www.kucoin.com/docs/rest/margin-trading/margin-trading-v3-/get-repayment-history @@ -6911,7 +6911,7 @@ def margin_get_repay_history(self, currency, isolated=False, symbol=None, order_ :type limit: int .. code:: python - + repay_history = client.margin_get_repay_history('USDT') :returns: ApiResponse @@ -6956,12 +6956,12 @@ def margin_get_repay_history(self, currency, isolated=False, symbol=None, order_ data['currentPage'] = page if limit: data['pageSize'] = limit - + return self._get('margin/repay', True, api_version=self.API_VERSION3, data=dict(data, **params)) - - def margin_get_cross_isolated_interest_records(self, isolated=False, symbol=None, currency=None, + + def margin_get_cross_isolated_interest_records(self, isolated=False, symbol=None, currency=None, start=None, end=None, page=None, limit=None, **params): - + """Get the cross or isolated margin interest records https://www.kucoin.com/docs/rest/margin-trading/margin-trading-v3-/get-cross-isolated-margin-interest-records @@ -7024,9 +7024,9 @@ def margin_get_cross_isolated_interest_records(self, isolated=False, symbol=None data['currentPage'] = page if limit: data['pageSize'] = limit - + return self._get('margin/interest', True, api_version=self.API_VERSION3, data=dict(data, **params)) - + def margin_get_cross_trading_pairs_config(self, symbol=None, **params): """Get the cross margin trading pairs configuration @@ -7078,13 +7078,13 @@ def margin_get_cross_trading_pairs_config(self, symbol=None, **params): data['symbol'] = symbol return self._get('margin/symbols', True, api_version=self.API_VERSION3, data=dict(data, **params)) - + def margin_modify_leverage_multiplier(self, leverage, symbol=None, isolated=False, **params): """Modify the leverage multiplier https://www.kucoin.com/docs/rest/margin-trading/margin-trading-v3-/modify-leverage-multiplier - :param leverage: Must be greater than 1 and up to two decimal places, + :param leverage: Must be greater than 1 and up to two decimal places, and cannot be less than the user's current debt leverage or greater than the system's maximum leverage :type leverage: int :param symbol: (optional) Name of symbol e.g. KCS-BTC @@ -7120,6 +7120,345 @@ def margin_modify_leverage_multiplier(self, leverage, symbol=None, isolated=Fals return self._post('position/update-user-leverage', True, api_version=self.API_VERSION3, data=dict(data, **params)) + # Lending Market Endpoints + + def margin_lending_get_currency_info(self, currency=None, **params): + """Get the lending currency info + + https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/get-currency-information + + :param currency: (optional) Currency + :type currency: string + + .. code:: python + + currency_info = client.lending_get_currency_info() + + :returns: ApiResponse + + .. code:: python + + { + "success": true, + "code": "200", + "msg": "success", + "retry": false, + "data": [ + { + "currency": "BTC", + "purchaseEnable": true, + "redeemEnable": true, + "increment": "1", + "minPurchaseSize": "10", + "minInterestRate": "0.004", + "maxInterestRate": "0.02", + "interestIncrement": "0.0001", + "maxPurchaseSize": "20000", + "marketInterestRate": "0.009", + "autoPurchaseEnable": true + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + + if currency: + data['currency'] = currency + + return self._get('project/list', False, api_version=self.API_VERSION3, data=dict(data, **params)) + + def margin_lending_get_interest_rate(self, currency, **params): + """ Get the interest rate for a currency + + https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/get-interest-rates + + :param currency: Currency + :type currency: string + + .. code:: python + + interest_rate = client.lending_get_interest_rate('BTC') + + :returns: ApiResponse + + .. code:: python + + { + "success": true, + "code": "200", + "msg": "success", + "retry": false, + "data": [ + { + "time": "202303261200", + "marketInterestRate": "0.003" + }, + { + "time": "202303261300", + "marketInterestRate": "0.004" + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'currency': currency + } + + return self._get('project/marketInterestRatet', False, api_version=self.API_VERSION3, data=dict(data, **params)) + + def margin_lending_subscribtion(self, currency, size, interest_rate, **params): + """ Subscribe to a lending product + + https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/subscription + + :param currency: Currency + :type currency: string + :param size: Amount to subscribe + :type size: string + :param interest_rate: Interest rate + :type interest_rate: string + + .. code:: python + + subscription = client.lending_subscribtion('BTC', '10', '0.004') + + :returns: ApiResponse + + .. code:: python + + { + "success": true, + "code": "200", + "msg": "success", + "retry": false, + "data": { + "orderNo": "5da6dba0f943c0c81f5d5db5" + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'currency': currency, + 'size': size, + 'interestRate': interest_rate + } + + return self._post('purchase', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def margin_lending_redemption(self, currency, size, purchase_order_no, **params): + """ Redeem a lending product + + https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/redemption + + :param currency: Currency + :type currency: string + :param size: Amount to redeem + :type size: string + :param purchase_order_no: OrderNo + :type purchase_order_no: string + + .. code:: python + + redemption = client.lending_redemption('BTC', '10', '5da6dba0f943c0c81f5d5db5') + + :returns: ApiResponse + + .. code:: python + + { + "success": true, + "code": "200", + "msg": "success", + "retry": false, + "data": { + "orderNo": "5da6dba0f943c0c81f5d5db5" + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'currency': currency, + 'size': size, + 'purchaseOrderNo': purchase_order_no + } + + return self._post('redeem', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def margin_lending_modify_subscription_orders(self, currency, purchase_order_no, interest_rate, **params): + """ Modify subscription orders + + https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/modify-subscription-orders + + :param currency: Currency + :type currency: string + :param purchase_order_no: OrderNo + :type purchase_order_no: string + :param interest_rate: Interest rate + :type interest_rate: string + + .. code:: python + + modify_subscription = client.lending_modify_subscription_orders('BTC', '5da6dba0f943c0c81f5d5db5', '0.004') + + :returns: ApiResponse + + .. code:: python + + { + "success": true, + "code": "200", + "msg": "success", + "retry": false + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'currency': currency, + 'purchaseOrderNo': purchase_order_no, + 'interestRate': interest_rate + } + + return self._post('lend/purchase/update', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def margin_lending_get_redemtion_orders(self, currency, status, redeem_order_no=None, page=None, limit=None, **params): + """ Get redemption orders + + https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/get-redemption-orders + + :param currency: Currency + :type currency: string + :param status: Status + :type status: string + :param redeem_order_no: (optional) OrderNo + :type redeem_order_no: string + :param page: (optional) Page number + :type page: int + :param limit: (optional) Number of orders + :type limit: int + + .. code:: python + + redemption_orders = client.lending_get_redemtion_orders('BTC', 'DONE') + + :returns: ApiResponse + + .. code:: python + + { + "currentPage": 1, + "pageSize": 100, + "totalNum": 1, + "totalPage": 1, + "items": [ + { + "currency": "BTC", + "purchaseOrderNo": "5da6dba0f943c0c81f5d5db5", + "redeemOrderNo": "5da6dbasdffga1f5d5dfsb5", + "redeemAmount": "300000", + "receiptAmount": "250000", + "applyTime": 1669508513820, + "status": "PENDING" + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'currency': currency, + 'status': status + } + + if redeem_order_no: + data['orderNo'] = redeem_order_no + if page: + data['currentPage'] = page + if limit: + data['pageSize'] = limit + + return self._get('redeem/orders', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def margin_lending_get_subscription_orders(self, currency, status, purchase_order_no=None, page=None, limit=None, **params): + """ Get subscription orders + + https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/get-subscription-orders + + :param currency: Currency + :type currency: string + :param status: Status + :type status: string + :param purchase_order_no: (optional) OrderNo + :type purchase_order_no: string + :param page: (optional) Page number + :type page: int + :param limit: (optional) Number of orders + :type limit: int + + .. code:: python + + subscription_orders = client.lending_get_subscription_orders('BTC', 'DONE') + + :returns: ApiResponse + + .. code:: python + + { + "currentPage": 1, + "pageSize": 100, + "totalNum": 1, + "totalPage": 1, + "items": [ + { + "currency": "BTC", + "purchaseOrderNo": "5da6dba0f943c0c81f5d5db5", + "purchaseAmount": "300000", + "lendAmount": "0", + "redeemAmount": "300000", + "interestRate": "0.0003", + "incomeAmount": "200", + "applyTime": 1669508513820, + "status": "DONE" + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'currency': currency, + 'status': status + } + + if purchase_order_no: + data['orderNo'] = purchase_order_no + if page: + data['currentPage'] = page + if limit: + data['pageSize'] = limit + + return self._get('purchase/orders', True, api_version=self.API_VERSION3, data=dict(data, **params)) + # Websocket Endpoints def get_ws_endpoint(self, private=False): From 8e158cab0864581857363d3009fba017118556bc Mon Sep 17 00:00:00 2001 From: rayBastard Date: Sun, 17 Nov 2024 20:09:35 +0100 Subject: [PATCH 49/60] margin_get_account_detail, margin_get_cross_account_detail added --- kucoin/client.py | 110 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) diff --git a/kucoin/client.py b/kucoin/client.py index 450f248..ecb5eb3 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -1139,6 +1139,116 @@ def get_subaccounts_v2(self, page=None, limit=None, **params): return self._get('sub/user', True, api_version=self.API_VERSION2, data=dict(data, **params)) + def margin_get_account_detail(self, **params): + """Get account detail + + https://www.kucoin.com/docs/rest/funding/funding-overview/get-account-detail-margin + + .. code:: python + + account = client.margin_get_account_detail() + + :returns: API Response + + .. code-block:: python + + { + "code": "200000", + "data": { + "debtRatio": "0", + "accounts": [ + { + "currency": "KCS", + "totalBalance": "0.01", + "availableBalance": "0.01", + "holdBalance": "0", + "liability": "0", + "maxBorrowSize": "0" + }, + { + "currency": "USDT", + "totalBalance": "0", + "availableBalance": "0", + "holdBalance": "0", + "liability": "0", + "maxBorrowSize": "0" + }, + ... + ] + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + return self._get('margin/account', True, data=params) + + def margin_get_cross_account_detail(self, quote_currency=None, query_type=None, **params): + """Get cross account detail + + https://www.kucoin.com/docs/rest/funding/funding-overview/get-account-detail-cross-margin + + :param quote_currency: (optional) quote currency + :type quote_currency: string + :param query_type: (optional) query type + :type query_type: string + + .. code:: python + + account = client.margin_get_cross_account_detail() + + :returns: API Response + + .. code-block:: python + + { + "success": true, + "code": "200", + "msg": "success", + "retry": false, + "data": { + "timestamp": 1669708513820, + "currentPage": 1, + "pageSize": 100, + "totalNum": 1, + "totalPage": 1, + "items": [ + { + "totalLiabilityOfQuoteCurrency": "0.976", + "totalAssetOfQuoteCurrency": "1.00", + "debtRatio": "0.976", + "status": "LIQUIDATION", + "assets": [ + { + "currency": "BTC", + "borrowEnabled": true, + "repayEnabled": true, + "transferEnabled": false, + "borrowed": "0.976", + "totalAsset": "1.00", + "available": "0.024", + "hold": "0", + "maxBorrowSize": "0" + } + ] + } + ] + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + if quote_currency: + data['quoteCurrency'] = quote_currency + if query_type: + data['type'] = query_type + + return self._get('margin/accounts', True, data=dict(data, **params)) + def get_subaccount_balance(self, sub_user_id, include_base_ammount, **params): """Get the account info of a sub-user specified by the subUserId From 1c1a2bd02e631d9ccecef6c9a107f53d4372a7f7 Mon Sep 17 00:00:00 2001 From: rayBastard Date: Sun, 17 Nov 2024 20:21:10 +0100 Subject: [PATCH 50/60] futures_get_all_subaccounts_balance, futures_get_account_detail, margin_get_isolated_account_detail added --- kucoin/client.py | 187 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 186 insertions(+), 1 deletion(-) diff --git a/kucoin/client.py b/kucoin/client.py index ecb5eb3..215191f 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -1247,8 +1247,123 @@ def margin_get_cross_account_detail(self, quote_currency=None, query_type=None, if query_type: data['type'] = query_type - return self._get('margin/accounts', True, data=dict(data, **params)) + return self._get('margin/accounts', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def margin_get_isolated_account_detail(self, symbol=None, quote_currency=None, query_type=None, **params): + """Get isolated account detail + https://www.kucoin.com/docs/rest/funding/funding-overview/get-account-detail-isolated-margin + + :param symbol: (optional) symbol + :type symbol: string + :param quote_currency: (optional) quote currency + :type quote_currency: string + :param query_type: (optional) query type + :type query_type: string + + .. code:: python + + account = client.margin_get_isolated_account_detail() + + :returns: API Response + + .. code-block:: python + + { + "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" + } + } + ] + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + if symbol: + data['symbol'] = symbol + if quote_currency: + data['quoteCurrency'] = quote_currency + if query_type: + data['type'] = query_type + + return self._get('isolated/accounts', True, api_version=self.API_VERSION3, data=dict(data, **params)) + + def futures_get_account_detail(self, currency=None, **params): + """Get futures account detail + + https://www.kucoin.com/docs/rest/funding/funding-overview/get-account-detail-futures + + :param currency: (optional) currency + :type currency: string + + .. code:: python + + account = client.futures_get_account_detail() + + :returns: API Response + + .. code-block:: python + + { + "code": "200000", + "data": { + "accountEquity": 99.8999305281, + "unrealisedPNL": 0, + "marginBalance": 99.8999305281, + "positionMargin": 0, + "orderMargin": 0, + "frozenFunds": 0, + "availableBalance": + "currency": "XBT" , + "riskRatio": 0 + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + if currency: + data['currency'] = currency + + return self._get('account-overview', True, data=dict(data, **params)) + def get_subaccount_balance(self, sub_user_id, include_base_ammount, **params): """Get the account info of a sub-user specified by the subUserId @@ -1435,6 +1550,76 @@ def get_all_subaccounts_balance_v2(self, page=None, limit=None, **params): data['pageSize'] = limit return self._get('sub-accounts', True, api_version=self.API_VERSION2, data=dict(data, **params)) + + def futures_get_all_subaccounts_balance(self, currency=None, **params): + """Get the account info of all sub-users + + https://www.kucoin.com/docs/rest/funding/funding-overview/get-all-sub-accounts-balance-futures + + :param currency: (optional) currency + :type currency: string + + .. code:: python + + accounts = client.futures_get_all_subaccounts_balance() + + :returns: API Response + + .. code-block:: python + + { + "success": true, + "code": "200", + "msg": "success", + "retry": false, + "data": { + "summary": { + "accountEquityTotal": 9.99, + "unrealisedPNLTotal": 0, + "marginBalanceTotal": 9.99, + "positionMarginTotal": 0, + "orderMarginTotal": 0, + "frozenFundsTotal": 0, + "availableBalanceTotal": 9.99, + "currency": "USDT" + }, + "accounts": [ + { + "accountName": "main", + "accountEquity": 9.99, + "unrealisedPNL": 0, + "marginBalance": 9.99, + "positionMargin": 0, + "orderMargin": 0, + "frozenFunds": 0, + "availableBalance": 9.99, + "currency": "USDT" + }, + { + "accountName": "subacct", + "accountEquity": 0, + "unrealisedPNL": 0, + "marginBalance": 0, + "positionMargin": 0, + "orderMargin": 0, + "frozenFunds": 0, + "availableBalance": 0, + "currency": "USDT" + } + ] + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + # todo check and add the response + + data = {} + if currency: + data['currency'] = currency + + return self._get('account-overview-all', True, data=dict(data, **params)) def get_subaccount_api_list(self, sub_name, api_key=None, **params): """Get the API key list of a sub-user From f841e009c3393d5a4d326c470620b42bc86c6eae Mon Sep 17 00:00:00 2001 From: rayBastard Date: Mon, 18 Nov 2024 23:27:18 +0100 Subject: [PATCH 51/60] futures market endpoints added futures_get_symbols futures_get_symbol futures_get_ticker futures_get_tickers futures_get_order_book futures_get_full_order_book futures_get_trade_histories futures_get_klines futures_get_interest_rate futures_get_index futures_get_mark_price futures_get_premium_index futures_get_24hr_stat --- kucoin/client.py | 810 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 804 insertions(+), 6 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 215191f..da3bef6 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -993,6 +993,804 @@ def get_fiat_prices(self, base=None, currencies=None, **params): return self._get('prices', False, data=dict(data, **params)) + # Futures Market Endpoints + + def futures_get_symbols(self, **params): + """Get a list of available currency pairs for trading. + + https://www.kucoin.com/docs/rest/futures-trading/market-data/get-symbols-list + + .. code:: python + + symbols = client.futures_get_symbols() + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "symbol": "XBTUSDTM", + "rootSymbol": "USDT", + "type": "FFWCSX", + "firstOpenDate": 1585555200000, + "expireDate": null, + "settleDate": null, + "baseCurrency": "XBT", + "quoteCurrency": "USDT", + "settleCurrency": "USDT", + "maxOrderQty": 1000000, + "maxPrice": 1000000.0, + "lotSize": 1, + "tickSize": 0.1, + "indexPriceTickSize": 0.01, + "multiplier": 0.001, + "initialMargin": 0.008, + "maintainMargin": 0.004, + "maxRiskLimit": 100000, + "minRiskLimit": 100000, + "riskStep": 50000, + "makerFeeRate": 2.0E-4, + "takerFeeRate": 6.0E-4, + "takerFixFee": 0.0, + "makerFixFee": 0.0, + "settlementFee": null, + "isDeleverage": true, + "isQuanto": true, + "isInverse": false, + "markMethod": "FairPrice", + "fairMethod": "FundingRate", + "fundingBaseSymbol": ".XBTINT8H", + "fundingQuoteSymbol": ".USDTINT8H", + "fundingRateSymbol": ".XBTUSDTMFPI8H", + "indexSymbol": ".KXBTUSDT", + "settlementSymbol": "", + "status": "Open", + "fundingFeeRate": 6.41E-4, + "predictedFundingFeeRate": 5.5E-5, + "fundingRateGranularity": 28800000, + "openInterest": "6273644", + "turnoverOf24h": 1.9110000807101517E9, + "volumeOf24h": 21807.101, + "markPrice": 87351.75, + "indexPrice": 87357.57, + "lastTradePrice": 87319.4, + "nextFundingRateTime": 1816952, + "maxLeverage": 125, + "sourceExchanges": [ + "okex", + "binance", + "kucoin", + "bybit", + "bitmart", + "gateio" + ], + "premiumsSymbol1M": ".XBTUSDTMPI", + "premiumsSymbol8H": ".XBTUSDTMPI8H", + "fundingBaseSymbol1M": ".XBTINT", + "fundingQuoteSymbol1M": ".USDTINT", + "lowPrice": 85201.8, + "highPrice": 90000.0, + "priceChgPct": -0.0033, + "priceChg": -291.0, + "k": 490.0, + "m": 300.0, + "f": 1.3, + "mmrLimit": 0.3, + "mmrLevConstant": 125.0, + "supportCross": true, + "buyLimit": 91717.92, + "sellLimit": 82982.88 + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + return self._get('contracts/active', False, data=params) + + def futures_get_symbol(self, symbol=None, **params): + """Get a symbol details for trading. + + https://www.kucoin.com/docs/rest/futures-trading/market-data/get-symbol-detail + + :param symbol: (optional) Name of symbol e.g. XBTUSDTM + :type symbol: string + + .. code:: python + + symbol = client.futures_get_symbol('XBTUSDTM') + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "symbol": "XBTUSDTM", + "rootSymbol": "USDT", + "type": "FFWCSX", + "firstOpenDate": 1585555200000, + "expireDate": null, + "settleDate": null, + "baseCurrency": "XBT", + "quoteCurrency": "USDT", + "settleCurrency": "USDT", + "maxOrderQty": 1000000, + "maxPrice": 1000000.0, + "lotSize": 1, + "tickSize": 0.1, + "indexPriceTickSize": 0.01, + "multiplier": 0.001, + "initialMargin": 0.008, + "maintainMargin": 0.004, + "maxRiskLimit": 100000, + "minRiskLimit": 100000, + "riskStep": 50000, + "makerFeeRate": 2.0E-4, + "takerFeeRate": 6.0E-4, + "takerFixFee": 0.0, + "makerFixFee": 0.0, + "settlementFee": null, + "isDeleverage": true, + "isQuanto": true, + "isInverse": false, + "markMethod": "FairPrice", + "fairMethod": "FundingRate", + "fundingBaseSymbol": ".XBTINT8H", + "fundingQuoteSymbol": ".USDTINT8H", + "fundingRateSymbol": ".XBTUSDTMFPI8H", + "indexSymbol": ".KXBTUSDT", + "settlementSymbol": "", + "status": "Open", + "fundingFeeRate": 6.41E-4, + "predictedFundingFeeRate": 5.5E-5, + "fundingRateGranularity": 28800000, + "openInterest": "6273644", + "turnoverOf24h": 1.9110000807101517E9, + "volumeOf24h": 21807.101, + "markPrice": 87351.75, + "indexPrice": 87357.57, + "lastTradePrice": 87319.4, + "nextFundingRateTime": 1816952, + "maxLeverage": 125, + "sourceExchanges": [ + "okex", + "binance", + "kucoin", + "bybit", + "bitmart", + "gateio" + ], + "premiumsSymbol1M": ".XBTUSDTMPI", + "premiumsSymbol8H": ".XBTUSDTMPI8H", + "fundingBaseSymbol1M": ".XBTINT", + "fundingQuoteSymbol1M": ".USDTINT", + "lowPrice": 85201.8, + "highPrice": 90000.0, + "priceChgPct": -0.0033, + "priceChg": -291.0, + "k": 490.0, + "m": 300.0, + "f": 1.3, + "mmrLimit": 0.3, + "mmrLevConstant": 125.0, + "supportCross": true, + "buyLimit": 91717.92, + "sellLimit": 82982.88 + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + + if symbol: + data['symbol'] = symbol + + return self._get('contracts/{}'.format(symbol), False, data=dict(data, **params)) + + def futures_get_ticker(self, symbol, **params): + """Get symbol ticker + + https://www.kucoin.com/docs/rest/futures-trading/market-data/get-ticker + + :param symbol: Name of symbol e.g. XBTUSDTM + + .. code:: python + + ticker = client.futures_get_ticker('XBTUSDTM') + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "sequence": 1001, + "symbol": + "side": "buy", + "size": 10, + "price": "7000.0", + "bestBidSize": 20, + "bestBidPrice": "7000.0", + "bestAskSize": 30, + "bestAskPrice": "7001.0", + "tradeId": "5cbd7377a6ffab0c7ba98b26", + "ts": 1550653727731 + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('ticker', False, data=dict(data, **params)) + + def futures_get_tickers(self, **params): + """Get symbol tickers + + https://www.kucoin.com/docs/rest/futures-trading/market-data/get-latest-ticker-for-all-contracts + + .. code:: python + + tickers = client.futures_get_tickers() + + :returns: ApiResponse + + .. code:: python + + { + "success": true, + "code": "200", + "msg": "success", + "retry": false, + "data": [ + { + "sequence": 1721456489271, + "symbol": "THETAUSDTM", + "side": "buy", + "size": 728, + "tradeId": "1721456489263", + "price": "1.479", + "bestBidPrice": "1.536", + "bestBidSize": 272, + "bestAskPrice": "1.54", + "bestAskSize": 1000, + "ts": 1722237164196000000 + } + ... + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + return self._get('allTickers', False, data=params) + + def futures_get_order_book(self, symbol, depth_20=False, **params): + """Get a list of bids and asks aggregated by price for a symbol. + + Returns up to 20 or 100 depth each side. Fastest Order book API + + https://www.kucoin.com/docs/rest/futures-trading/market-data/get-part-order-book-level-2 + + :param symbol: Name of symbol e.g. XBTUSDTM + + .. code:: python + + orders = client.futures_get_order_book('XBTUSDTM') + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "symbol": "XBTUSDM", + "sequence": 100, + "asks": [ + ["5000.0", 1000], + ["6000.0", 1983] + ], + "bids": [ + ["3200.0", 800], + ["3100.0", 100] + ], + "ts": 1604643655040584408 + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + path = 'level2/depth' + if depth_20: + path += '20' + else: + path += '100' + + return self._get(path, False, data=dict(data, **params)) + + def futures_get_full_order_book(self, symbol, **params): + """Get a list of all bids and asks aggregated by price for a symbol. + + This call is generally used by professional traders because it uses more server resources and traffic, + + https://www.kucoin.com/docs/rest/futures-trading/market-data/get-full-order-book-level-2 + + :param symbol: Name of symbol e.g. XBTUSDTM + + .. code:: python + + orders = client.futures_get_full_order_book('XBTUSDTM') + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "symbol": "XBTUSDM", + "sequence": 100, + "asks": [ + ["5000.0", 1000], + ["6000.0", 1983] + ], + "bids": [ + ["3200.0", 800], + ["3100.0", 100] + ], + "ts": 1604643655040584408 + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('level2/snapshot', False, data=dict(data, **params)) + + def futures_get_trade_histories(self, symbol, **params): + """List the latest trades for a symbol + + https://www.kucoin.com/docs/rest/futures-trading/market-data/get-transaction-history + + :param symbol: Name of symbol e.g. XBTUSDTM + + .. code:: python + + orders = client.futures_get_trade_histories('XBTUSDTM') + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "sequence": 102, + "tradeId": "5cbd7377a6ffab0c7ba98b26", + "takerOrderId": "5cbd7377a6ffab0c7ba98b27", + "makerOrderId": "5cbd7377a6ffab0c7ba98b28", + "price": "7000.0", + "size": 1, + "side": "buy", + "ts": 1545904567062140823 + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('trade/history', False, data=dict(data, **params)) + + def futures_get_klines(self, symbol, kline_type='5min', start=None, end=None, **params): + """Get kline data + + https://www.kucoin.com/docs/rest/futures-trading/market-data/get-klines + + For each query, the system would return at most 1500 pieces of data. + + :param symbol: Name of symbol e.g. XBTUSDTM + :type symbol: string + :param kline_type: type of symbol, type of candlestick patterns: 1min, 3min, 5min, 15min, 30min, 1hour, 2hour, + 4hour, 6hour, 8hour, 12hour, 1day, 1week + :type kline_type: string + :param start: Start time as unix timestamp (optional) default start of day in UTC + :type start: int + :param end: End time as unix timestamp (optional) default now in UTC + :type end: int + + .. code:: python + + klines = client.futures_get_klines('XBTUSDTM', '5min', 1507479171, 1510278278) + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": [ + [ + 1575331200000, + 7495.01, + 8309.67, + 7250, + 7463.55, + 0 + ], + [ + 1575374400000, + 7464.37, + 8297.85, + 7273.02, + 7491.44, + 0 + ] + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol, + 'granularity': kline_type + } + + if start is not None: + data['from'] = start + if end is not None: + data['to'] = end + + return self._get('kline/query', False, data=dict(data, **params)) + + def futures_get_interest_rate(self, symbol, start=None, end=None, reverse=True, + offset=None, forward=False, max_count=None, **params): + """Get interest rate + + https://www.kucoin.com/docs/rest/futures-trading/market-data/get-interest-rate-list + + :param symbol: Name of symbol e.g. XBTUSDTM + :type symbol: string + :param start: Start time as unix timestamp (optional) default start of day in UTC + :type start: int + :param end: End time as unix timestamp (optional) default now in UTC + :type end: int + :param reverse: (optional) True means “yes”. False means no. This parameter is set as True by default. + :type reverse: bool + :param offset: (optional) Start offset. The unique attribute of the last returned result of the last request. + The data of the first page will be returned by default. + :type offset: int + :param forward: (optional) True means “yes”. False means no. This parameter is set as False by default. + :type forward: bool + :param max_count: (optional) Maximum number of data to return. The default value is 100. + :type max_count: int + + .. code:: python + + interest_rate = client.futures_get_interest_rate('XBTUSDTM') + + :returns: ApiResponse + + .. code:: python + + { + "dataList": [ + { + "symbol": ".XBTINT", + "granularity": 60000, + "timePoint": 1557996300000, + "value": 0.0003 + }, + { + "symbol": ".XBTINT", + "granularity": 60000, + "timePoint": 1557996240000, + "value": 0.0003 + }, + { + "symbol": ".XBTINT", + "granularity": 60000, + "timePoint": 1557996180000, + "value": 0.0003 + } + ], + "hasMore": true + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + if start is not None: + data['startAt'] = start + if end is not None: + data['endAt'] = end + if reverse is not None: + data['reverse'] = reverse + if offset is not None: + data['offset'] = offset + if forward is not None: + data['forward'] = forward + if max_count is not None: + data['maxCount'] = max_count + + return self._get('interest/query', False, data=dict(data, **params)) + + def futures_get_index(self, symbol, start=None, end=None, reverse=True, + offset=None, forward=False, max_count=None, **params): + """Get index + + https://www.kucoin.com/docs/rest/futures-trading/market-data/get-index-list + + :param symbol: Name of symbol e.g. XBTUSDTM + :type symbol: string + :param start: Start time as unix timestamp (optional) default start of day in UTC + :type start: int + :param end: End time as unix timestamp (optional) default now in UTC + :type end: int + :param reverse: (optional) True means “yes”. False means no. This parameter is set as True by default. + :type reverse: bool + :param offset: (optional) Start offset. The unique attribute of the last returned result of the last request. + The data of the first page will be returned by default. + :type offset: int + :param forward: (optional) True means “yes”. False means no. This parameter is set as False by default. + :type forward: bool + :param max_count: (optional) Maximum number of data to return. The default value is 100. + :type max_count: int + + :param symbol: Name of symbol e.g. XBTUSDTM + + .. code:: python + + index = client.futures_get_index('XBTUSDTM') + + :returns: ApiResponse + + .. code:: python + + { + "dataList": [ + { + "symbol": ".KXBT", + "granularity": 1000, + "timePoint": 1557998570000, + "value": 8016.24, + "decomposionList": [ + { + "exchange": "gemini", + "price": 8016.24, + "weight": 0.08042611 + }, + { + "exchange": "kraken", + "price": 8016.24, + "weight": 0.02666502 + }, + { + "exchange": "coinbase", + "price": 8016.24, + "weight": 0.03847059 + }, + { + "exchange": "liquid", + "price": 8016.24, + "weight": 0.20419723 + }, + { + "exchange": "bittrex", + "price": 8016.24, + "weight": 0.29848962 + }, + { + "exchange": "bitstamp", + "price": 8016.24, + "weight": 0.35175143 + } + ] + } + ], + "hasMore": true + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + if start is not None: + data['startAt'] = start + if end is not None: + data['endAt'] = end + if reverse is not None: + data['reverse'] = reverse + if offset is not None: + data['offset'] = offset + if forward is not None: + data['forward'] = forward + if max_count is not None: + data['maxCount'] = max_count + + return self._get('index/query', False, data=dict(data, **params)) + + def futures_get_mark_price(self, symbol, **params): + """Get mark price + + https://www.kucoin.com/docs/rest/futures-trading/market-data/get-current-mark-price + + :param symbol: Name of symbol e.g. XBTUSDTM + :type symbol: string + + .. code:: python + + mark_price = client.futures_get_mark_price('XBTUSDTM') + + :returns: ApiResponse + + .. code:: python + + { + "symbol": "XBTUSDM", + "granularity": 1000, + "timePoint": 1557999585000, + "value": 8052.51, + "indexPrice": 8041.95 + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('mark-price/{}/current'.format(symbol), False, data=dict(data, **params)) + + def futures_get_premium_index(self, symbol, start=None, end=None, reverse=True, + offset=None, forward=False, max_count=None, **params): + """Get premium index + + https://www.kucoin.com/docs/rest/futures-trading/market-data/get-premium-index + + :param symbol: Name of symbol e.g. XBTUSDTM + :type symbol: string + :param start: Start time as unix timestamp (optional) default start of day in UTC + :type start: int + :param end: End time as unix timestamp (optional) default now in UTC + :type end: int + :param reverse: (optional) True means “yes”. False means no. This parameter is set as True by default. + :type reverse: bool + :param offset: (optional) Start offset. The unique attribute of the last returned result of the last request. + The data of the first page will be returned by default. + :type offset: int + :param forward: (optional) True means “yes”. False means no. This parameter is set as False by default. + :type forward: bool + :param max_count: (optional) Maximum number of data to return. The default value is 100. + :type max_count: int + + .. code:: python + + premium_index = client.futures_get_premium_index('XBTUSDTM') + + :returns: ApiResponse + + .. code:: python + + { + "dataList": [ + { + "symbol": ".XBTUSDMPI", + "granularity": 60000, + "timePoint": 1558000320000, + "value": 0.022585 + }, + { + "symbol": ".XBTUSDMPI", + "granularity": 60000, + "timePoint": 1558000260000, + "value": 0.022611 + }, + { + "symbol": ".XBTUSDMPI", + "granularity": 60000, + "timePoint": 1558000200000, + "value": 0.021421 + } + ], + "hasMore": true + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + if start is not None: + data['startAt'] = start + if end is not None: + data['endAt'] = end + if reverse is not None: + data['reverse'] = reverse + if offset is not None: + data['offset'] = offset + if forward is not None: + data['forward'] = forward + if max_count is not None: + data['maxCount'] = max_count + + return self._get('premium/query', False, data=dict(data, **params)) + + def futures_get_24hr_stats(self, **params): + """Get 24hr stats + + https://www.kucoin.com/docs/rest/futures-trading/market-data/get-24hour-futures-transaction-volume + + .. code:: python + + stats = client.futures_get_24hr_stats() + + :returns: ApiResponse + + .. code:: python + + { + "success": true, + "code": "200", + "msg": "success", + "retry": false, + "data": { + "turnoverOf24h": 619 + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + return self._get('24hrStats', False, data=params) + # User Account Endpoints def get_accounts(self, currency=None, account_type=None, **params): @@ -1248,7 +2046,7 @@ def margin_get_cross_account_detail(self, quote_currency=None, query_type=None, data['type'] = query_type return self._get('margin/accounts', True, api_version=self.API_VERSION3, data=dict(data, **params)) - + def margin_get_isolated_account_detail(self, symbol=None, quote_currency=None, query_type=None, **params): """Get isolated account detail @@ -1322,7 +2120,7 @@ def margin_get_isolated_account_detail(self, symbol=None, quote_currency=None, q data['type'] = query_type return self._get('isolated/accounts', True, api_version=self.API_VERSION3, data=dict(data, **params)) - + def futures_get_account_detail(self, currency=None, **params): """Get futures account detail @@ -1345,12 +2143,12 @@ def futures_get_account_detail(self, currency=None, **params): "accountEquity": 99.8999305281, "unrealisedPNL": 0, "marginBalance": 99.8999305281, - "positionMargin": 0, + "positionMargin": 0, "orderMargin": 0, "frozenFunds": 0, "availableBalance": "currency": "XBT" , - "riskRatio": 0 + "riskRatio": 0 } } @@ -1363,7 +2161,7 @@ def futures_get_account_detail(self, currency=None, **params): data['currency'] = currency return self._get('account-overview', True, data=dict(data, **params)) - + def get_subaccount_balance(self, sub_user_id, include_base_ammount, **params): """Get the account info of a sub-user specified by the subUserId @@ -1550,7 +2348,7 @@ def get_all_subaccounts_balance_v2(self, page=None, limit=None, **params): data['pageSize'] = limit return self._get('sub-accounts', True, api_version=self.API_VERSION2, data=dict(data, **params)) - + def futures_get_all_subaccounts_balance(self, currency=None, **params): """Get the account info of all sub-users From b60c60c1b3eb65a0f4b9b1010c7147e0d511344b Mon Sep 17 00:00:00 2001 From: rayBastard Date: Mon, 18 Nov 2024 23:42:35 +0100 Subject: [PATCH 52/60] typo fixed --- kucoin/client.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kucoin/client.py b/kucoin/client.py index da3bef6..c37d164 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -1789,7 +1789,7 @@ def futures_get_24hr_stats(self, **params): """ - return self._get('24hrStats', False, data=params) + return self._get('trade-statistics', False, data=params) # User Account Endpoints From 036ac0b7e9cfed75719ec9c437e5d6f21a91f6b1 Mon Sep 17 00:00:00 2001 From: rayBastard Date: Tue, 19 Nov 2024 00:14:06 +0100 Subject: [PATCH 53/60] futures fills added futures_get_fills futures_get_recent_fills futures_get_active_order_value --- kucoin/client.py | 182 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 182 insertions(+) diff --git a/kucoin/client.py b/kucoin/client.py index c37d164..127ed48 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -7364,6 +7364,188 @@ def hf_margin_get_fills(self, symbol, trade_type, order_id=None, side=None, type return self._get('hf/margin/fills', True, api_version=self.API_VERSION3, data=dict(data, **params)) + def futures_get_fills(self, order_id=None, symbol=None, side=None, type=None, start=None, end=None, page=None, limit=None, **params): + """Get a list of recent futures fills. + + https://www.kucoin.com/docs/rest/futures-trading/fills/get-filled-list + + :param order_id: (optional) OrderId + :type order_id: string + :param symbol: (optional) Name of symbol e.g. KCS-BTC + :type symbol: string + :param side: (optional) buy or sell + :type side: string + :param type: (optional) limit, market, limit_stop or market_stop + :type type: string + :param start: (optional) Start time as unix timestamp + :type start: int + :param end: (optional) End time as unix timestamp + :type end: int + :param page: (optional) Page number + :type page: int + :param limit: (optional) Number of orders + :type limit: int + + .. code:: python + + fills = client.futures_get_fills() + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "currentPage": 1, + "pageSize": 1, + "totalNum": 251915, + "totalPage": 251915, + "items": [ + { + "symbol": "XBTUSDM", + "tradeId": "5ce24c1f0c19fc3c58edc47c", + "orderId": "5ce24c16b210233c36ee321d", + "side": "sell", + "liquidity": "taker", + "forceTaker": true, + "price": "8302", + "size": 10, + "value": "0.001204529", + "feeRate": "0.0005", + "fixFee": "0.00000006", + "feeCurrency": "XBT", + "stop": "", + "fee": "0.0000012022", + "orderType": "limit", + "tradeType": "trade", + "createdAt": 1558334496000, + "settleCurrency": "XBT", + "openFeePay": "0.002", + "closeFeePay": "0.002", + "tradeTime": 1558334496000000000, + "marginMode": "ISOLATED" + } + ] + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + + if order_id: + data['orderId'] = order_id + if symbol: + data['symbol'] = symbol + if side: + data['side'] = side + if type: + data['type'] = type + if start: + data['startAt'] = start + if end: + data['endAt'] = end + if page: + data['currentPage'] = page + if limit: + data['pageSize'] = limit + + return self._get('fills', False, data=dict(data, **params)) + + def futures_get_recent_fills(self, symbol=None, **params): + """Get a list of recent futures fills. + + https://www.kucoin.com/docs/rest/futures-trading/fills/get-recent-filled-list + + .. code:: python + + fills = client.futures_get_recent_fills() + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": [ + { + "symbol": "XBTUSDM", + "tradeId": "5ce24c1f0c19fc3c58edc47c", + "orderId": "5ce24c16b210233c36ee321d", + "side": "sell", + "liquidity": "taker", + "forceTaker": true, + "price": "8302", + "size": 10, + "value": "0.001204529", + "feeRate": "0.0005", + "fixFee": "0.00000006", + "feeCurrency": "XBT", + "stop": "", + "fee": "0.0000012022", + "orderType": "limit", + "tradeType": "trade", + "createdAt": 1558334496000, + "settleCurrency": "XBT", + "openFeePay": "0.002", + "closeFeePay": "0.002", + "tradeTime": 1558334496000000000, + "marginMode": "ISOLATED" + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + + if symbol: + data['symbol'] = symbol + + return self._get('recentFills', False, data=dict(data, **params)) + + def futures_get_active_order_value(self, symbol, **params): + """Get the active order value of a symbol + + https://www.kucoin.com/docs/rest/futures-trading/fills/get-active-order-value-calculation + + :param symbol: Name of symbol e.g. XBTUSDM + :type symbol: string + + .. code:: python + + active_order_value = client.futures_get_active_order_value('XBTUSDM') + + :returns: ApiResponse + + .. code:: python + + { + "code": "200000", + "data": { + "openOrderBuySize": 20, + "openOrderSellSize": 0, + "openOrderBuyCost": "0.0025252525", + "openOrderSellCost": "0", + "settleCurrency": "XBT" + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('openOrderStatistics', False, data=dict(data, **params)) + # Margin Info Endpoints def margin_get_leverage_token_info(self, currency=None, **params): From 44e7d42b0d245c5441b394679d1b62855b51ac15 Mon Sep 17 00:00:00 2001 From: rayBastard Date: Tue, 19 Nov 2024 00:21:22 +0100 Subject: [PATCH 54/60] futures_get_risk_limit_level, futures_modify_risk_limit_level added --- kucoin/client.py | 84 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 82 insertions(+), 2 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 127ed48..bd706cf 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -7662,8 +7662,6 @@ def margin_get_mark_price(self, symbol, **params): return self._get('mark-price/{}/current'.format(symbol), False, data=dict(data, **params)) - - def margin_get_config(self, **params): """Get the margin configuration @@ -8734,6 +8732,88 @@ def margin_lending_get_subscription_orders(self, currency, status, purchase_orde return self._get('purchase/orders', True, api_version=self.API_VERSION3, data=dict(data, **params)) + # Futures Risk Limit Endpoints + + def futures_get_risk_limit_level(self, symbol, **params): + """Get the risk limit level for a symbol + + https://www.kucoin.com/docs/rest/futures-trading/risk-limit/get-futures-risk-limit-level + + :param symbol: Name of symbol e.g. XBTUSDM + :type symbol: string + + .. code:: python + + risk_limit_level = client.futures_get_risk_limit_level('XBTUSDM') + + :returns: ApiResponse + + { + "code": "200000", + "data": [ + { + "symbol": "ADAUSDTM", + "level": 1, + "maxRiskLimit": 500, + "minRiskLimit": 0, + "maxLeverage": 20, + "initialMargin": 0.05, + "maintainMargin": 0.025 + }, + { + "symbol": "ADAUSDTM", + "level": 2, + "maxRiskLimit": 1000, + "minRiskLimit": 500, + "maxLeverage": 2, + "initialMargin": 0.5, + "maintainMargin": 0.25 + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('contracts/risk-limit{}'.format(symbol), True, data=dict(data, **params)) + + def futures_modify_risk_limit_level(self, symbol, level, **params): + """Modify the risk limit level for a symbol + + https://www.kucoin.com/docs/rest/futures-trading/risk-limit/modify-risk-limit-level + + :param symbol: Name of symbol e.g. XBTUSDM + :type symbol: string + :param level: Risk limit level + :type level: int + + .. code:: python + + risk_limit_level = client.futures_modify_risk_limit_level('XBTUSDM', 2) + + :returns: ApiResponse + + { + "code": "200000", + "data": true + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol, + 'level': level + } + + return self._post('position/risk-limit-level/change', True, data=dict(data, **params)) + # Websocket Endpoints def get_ws_endpoint(self, private=False): From 3ba73a79b39ea21f6b6b98c387a3b1cff874a846 Mon Sep 17 00:00:00 2001 From: rayBastard Date: Tue, 19 Nov 2024 00:33:18 +0100 Subject: [PATCH 55/60] Futures Funding Fees Endpoints added futures_get_funding_rate futures_get_public_funding_history futures_get_private_funding_history --- kucoin/client.py | 173 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 173 insertions(+) diff --git a/kucoin/client.py b/kucoin/client.py index bd706cf..b555404 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -8814,6 +8814,179 @@ def futures_modify_risk_limit_level(self, symbol, level, **params): return self._post('position/risk-limit-level/change', True, data=dict(data, **params)) + # Futures Funding Fees Endpoints + + def futures_get_funding_rate(self, symbol, **params): + """Get the funding rate for a symbol + + https://www.kucoin.com/docs/rest/futures-trading/funding-fees/get-current-funding-rate + + :param symbol: Name of symbol e.g. XBTUSDM + :type symbol: string + + .. code:: python + + funding_rate = client.futures_get_funding_rate('XBTUSDM') + + :returns: ApiResponse + + { + "code": "200000", + "data": { + "symbol": ".XBTUSDTMFPI8H", + "granularity": 28800000, + "timePoint": 1731441600000, + "value": 0.000641, + "predictedValue": 0.000052, + "fundingRateCap": 0.003, + "fundingRateFloor": -0.003 + } + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('funding-rate/{}/current'.format(symbol), True, data=dict(data, **params)) + + def futures_get_public_funding_history(self, symbol, start, end, **params): + """Get the public funding history for a symbol + + https://www.kucoin.com/docs/rest/futures-trading/funding-fees/get-public-funding-history + + :param symbol: Name of symbol e.g. XBTUSDM + :type symbol: string + :param start: Start time as unix timestamp + :type start: int + :param end: End time as unix timestamp + :type end: int + + .. code:: python + + funding_history = client.futures_get_public_funding_history('XBTUSDM', 1669508513820, 1669508513820) + + :returns: ApiResponse + + { + "success": true, + "code": "200", + "msg": "success", + "retry": false, + "data": [ + { + "symbol": "IDUSDTM", + "fundingRate": 0.018750, + "timepoint": 1702310700000 + } + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol, + 'from': start, + 'to': end + } + + return self._get('contract/funding-rates', False, data=dict(data, **params)) + + def futures_get_private_funding_history(self, symbol, start=None, end=None, reverse=True, + offset=None, forward=False, max_count=None, **params): + """Get the private funding history for a symbol + + https://www.kucoin.com/docs/rest/futures-trading/funding-fees/get-private-funding-history + + :param symbol: Name of symbol e.g. XBTUSDM + :type symbol: string + :param start: (optional) Start time as unix timestamp + :type start: int + :param end: (optional) End time as unix timestamp + :type end: int + :param reverse: (optional) Reverse the results + :type reverse: bool + :param offset: (optional) Offset + :type offset: int + :param forward: (optional) Forward the results + :type forward: bool + :param max_count: (optional) Maximum number of results + :type max_count: int + + .. code:: python + + funding_history = client.futures_get_private_funding_history('XBTUSDM') + + :returns: ApiResponse + + { + "dataList": [ + { + "id": 36275152660006, + "symbol": "XBTUSDM", + "timePoint": 1557918000000, + "fundingRate": 0.000013, + "markPrice": 8058.27, + "positionQty": 10, + "positionCost": -0.001241, + "funding": -0.00000464, + "settleCurrency": "XBT" + }, + { + "id": 36275152660004, + "symbol": "XBTUSDM", + "timePoint": 1557914400000, + "fundingRate": 0.00375, + "markPrice": 8079.65, + "positionQty": 10, + "positionCost": -0.0012377, + "funding": -0.00000465, + "settleCurrency": "XBT" + }, + { + "id": 36275152660002, + "symbol": "XBTUSDM", + "timePoint": 1557910800000, + "fundingRate": 0.00375, + "markPrice": 7889.03, + "positionQty": 10, + "positionCost": -0.0012676, + "funding": -0.00000476, + "settleCurrency": "XBT" + } + ], + "hasMore": true + } + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + if start: + data['startAt'] = start + if end: + data['endAt'] = end + if reverse: + data['reverse'] = reverse + if offset: + data['offset'] = offset + if forward: + data['forward'] = forward + if max_count: + data['maxCount'] = max_count + + return self._get('funding-history', True, data=dict(data, **params)) + + # Websocket Endpoints def get_ws_endpoint(self, private=False): From 24b19c328cba7fa00a4a04b5a0508c23816d2e67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Tue, 19 Nov 2024 15:16:43 +0300 Subject: [PATCH 56/60] base url updated for futures endpoints --- kucoin/client.py | 68 +++++++++++++++++++++++------------------------- 1 file changed, 33 insertions(+), 35 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index b555404..6ba1037 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -14,7 +14,8 @@ class Client(object): - REST_API_URL = 'https://openapi-v2.kucoin.com' + REST_API_URL = 'https://api.kucoin.com' + REST_FUTURES_API_URL = 'https://api-futures.kucoin.com' # SANDBOX_API_URL = 'https://openapi-sandbox.kucoin.com' # does not supported anymore API_VERSION = 'v1' API_VERSION2 = 'v2' @@ -79,6 +80,7 @@ def __init__(self, api_key, api_secret, passphrase, sandbox=False, requests_para raise KucoinAPIException('Sandbox mode is not supported anymore. See https://www.kucoin.com/docs/beginners/sandbox. To test orders, use test methods (e.g. create_test_order)') else: self.API_URL = self.REST_API_URL + self.FUTURES_API_URL = self.REST_FUTURES_API_URL self._requests_params = requests_params self.session = self._init_session() @@ -137,10 +139,11 @@ def _create_path(self, path, api_version=None): api_version = api_version or self.API_VERSION return '/api/{}/{}'.format(api_version, path) - def _create_uri(self, path): - return '{}{}'.format(self.API_URL, path) + def _create_uri(self, path, is_futures=False): + base_url = self.FUTURES_API_URL if is_futures else self.API_URL + return '{}{}'.format(base_url, path) - def _request(self, method, path, signed, api_version=None, **kwargs): + def _request(self, method, path, signed, api_version=None, is_futures=False, **kwargs): # set default requests timeout kwargs['timeout'] = 10 @@ -153,7 +156,7 @@ def _request(self, method, path, signed, api_version=None, **kwargs): kwargs['headers'] = kwargs.get('headers', {}) full_path = self._create_path(path, api_version) - uri = self._create_uri(full_path) + uri = self._create_uri(full_path, is_futures) if signed: # generate signature @@ -201,17 +204,17 @@ def _handle_response(response): except ValueError: raise KucoinRequestException('Invalid Response: %s' % response.text) - def _get(self, path, signed=False, api_version=None, **kwargs): - return self._request('get', path, signed, api_version, **kwargs) + def _get(self, path, signed=False, api_version=None, is_futures=False, **kwargs): + return self._request('get', path, signed, api_version, is_futures, **kwargs) - def _post(self, path, signed=False, api_version=None, **kwargs): - return self._request('post', path, signed, api_version, **kwargs) + def _post(self, path, signed=False, api_version=None, is_futures=False, **kwargs): + return self._request('post', path, signed, api_version, is_futures, **kwargs) - def _put(self, path, signed=False, api_version=None, **kwargs): - return self._request('put', path, signed, api_version, **kwargs) + def _put(self, path, signed=False, api_version=None, is_futures=False, **kwargs): + return self._request('put', path, signed, api_version, is_futures, **kwargs) - def _delete(self, path, signed=False, api_version=None, **kwargs): - return self._request('delete', path, signed, api_version, **kwargs) + def _delete(self, path, signed=False, api_version=None, is_futures=False, **kwargs): + return self._request('delete', path, signed, api_version, is_futures, **kwargs) def get_timestamp(self): """Get the server timestamp @@ -1089,14 +1092,14 @@ def futures_get_symbols(self, **params): """ - return self._get('contracts/active', False, data=params) + return self._get('contracts/active', False, is_futures=True, data=params) - def futures_get_symbol(self, symbol=None, **params): + def futures_get_symbol(self, symbol, **params): """Get a symbol details for trading. https://www.kucoin.com/docs/rest/futures-trading/market-data/get-symbol-detail - :param symbol: (optional) Name of symbol e.g. XBTUSDTM + :param symbol: Name of symbol e.g. XBTUSDTM :type symbol: string .. code:: python @@ -1188,12 +1191,7 @@ def futures_get_symbol(self, symbol=None, **params): """ - data = {} - - if symbol: - data['symbol'] = symbol - - return self._get('contracts/{}'.format(symbol), False, data=dict(data, **params)) + return self._get('contracts/{}'.format(symbol), False, is_futures=True, data=params) def futures_get_ticker(self, symbol, **params): """Get symbol ticker @@ -1235,7 +1233,7 @@ def futures_get_ticker(self, symbol, **params): 'symbol': symbol } - return self._get('ticker', False, data=dict(data, **params)) + return self._get('ticker', False, is_futures=True, data=dict(data, **params)) def futures_get_tickers(self, **params): """Get symbol tickers @@ -1277,7 +1275,7 @@ def futures_get_tickers(self, **params): """ - return self._get('allTickers', False, data=params) + return self._get('allTickers', False, is_futures=True, data=params) def futures_get_order_book(self, symbol, depth_20=False, **params): """Get a list of bids and asks aggregated by price for a symbol. @@ -1327,7 +1325,7 @@ def futures_get_order_book(self, symbol, depth_20=False, **params): else: path += '100' - return self._get(path, False, data=dict(data, **params)) + return self._get(path, False, is_futures=True, data=dict(data, **params)) def futures_get_full_order_book(self, symbol, **params): """Get a list of all bids and asks aggregated by price for a symbol. @@ -1371,7 +1369,7 @@ def futures_get_full_order_book(self, symbol, **params): 'symbol': symbol } - return self._get('level2/snapshot', False, data=dict(data, **params)) + return self._get('level2/snapshot', False, is_futures=True, data=dict(data, **params)) def futures_get_trade_histories(self, symbol, **params): """List the latest trades for a symbol @@ -1410,7 +1408,7 @@ def futures_get_trade_histories(self, symbol, **params): 'symbol': symbol } - return self._get('trade/history', False, data=dict(data, **params)) + return self._get('trade/history', False, is_futures=True, data=dict(data, **params)) def futures_get_klines(self, symbol, kline_type='5min', start=None, end=None, **params): """Get kline data @@ -1473,7 +1471,7 @@ def futures_get_klines(self, symbol, kline_type='5min', start=None, end=None, ** if end is not None: data['to'] = end - return self._get('kline/query', False, data=dict(data, **params)) + return self._get('kline/query', False, is_futures=True, data=dict(data, **params)) def futures_get_interest_rate(self, symbol, start=None, end=None, reverse=True, offset=None, forward=False, max_count=None, **params): @@ -1550,7 +1548,7 @@ def futures_get_interest_rate(self, symbol, start=None, end=None, reverse=True, if max_count is not None: data['maxCount'] = max_count - return self._get('interest/query', False, data=dict(data, **params)) + return self._get('interest/query', False, is_futures=True, data=dict(data, **params)) def futures_get_index(self, symbol, start=None, end=None, reverse=True, offset=None, forward=False, max_count=None, **params): @@ -1649,7 +1647,7 @@ def futures_get_index(self, symbol, start=None, end=None, reverse=True, if max_count is not None: data['maxCount'] = max_count - return self._get('index/query', False, data=dict(data, **params)) + return self._get('index/query', False, is_futures=True, data=dict(data, **params)) def futures_get_mark_price(self, symbol, **params): """Get mark price @@ -1683,7 +1681,7 @@ def futures_get_mark_price(self, symbol, **params): 'symbol': symbol } - return self._get('mark-price/{}/current'.format(symbol), False, data=dict(data, **params)) + return self._get('mark-price/{}/current'.format(symbol), False, is_futures=True, data=dict(data, **params)) def futures_get_premium_index(self, symbol, start=None, end=None, reverse=True, offset=None, forward=False, max_count=None, **params): @@ -1760,16 +1758,16 @@ def futures_get_premium_index(self, symbol, start=None, end=None, reverse=True, if max_count is not None: data['maxCount'] = max_count - return self._get('premium/query', False, data=dict(data, **params)) + return self._get('premium/query', False, is_futures=True, data=dict(data, **params)) - def futures_get_24hr_stats(self, **params): + def futures_get_24hr_transaction_volume(self, **params): """Get 24hr stats https://www.kucoin.com/docs/rest/futures-trading/market-data/get-24hour-futures-transaction-volume .. code:: python - stats = client.futures_get_24hr_stats() + stats = client.futures_get_24hr_transaction_volume() :returns: ApiResponse @@ -1789,7 +1787,7 @@ def futures_get_24hr_stats(self, **params): """ - return self._get('trade-statistics', False, data=params) + return self._get('trade-statistics', False, is_futures=True, data=params) # User Account Endpoints From 4c4f56836fb6c7444198d780a9a2a3b5326d52c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Tue, 19 Nov 2024 20:32:25 +0300 Subject: [PATCH 57/60] futures_create_order, futures_create_test_order and futures_create_stop_order added --- kucoin/client.py | 460 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 455 insertions(+), 5 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 6ba1037..46e8842 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -216,7 +216,7 @@ def _put(self, path, signed=False, api_version=None, is_futures=False, **kwargs) def _delete(self, path, signed=False, api_version=None, is_futures=False, **kwargs): return self._request('delete', path, signed, api_version, is_futures, **kwargs) - def get_timestamp(self): + def get_timestamp(self, **params): """Get the server timestamp https://www.kucoin.com/docs/rest/spot-trading/market-data/get-server-time @@ -224,9 +224,19 @@ def get_timestamp(self): :return: response timestamp in ms """ - return self._get("timestamp") + return self._get("timestamp", data=params) - def get_status(self): + def futures_get_timestamp(self, **params): + """Get the futures server timestamp + + https://www.kucoin.com/docs/rest/futures-trading/market-data/get-server-time + + :return: response timestamp in ms + + """ + return self._get("timestamp", is_futures=True, data=params) + + def get_status(self, **params): """Get the service status https://www.kucoin.com/docs/rest/spot-trading/market-data/get-service-status @@ -244,7 +254,27 @@ def get_status(self): } """ - return self._get("status") + return self._get("status", data=params) + + def futures_get_status(self, **params): + """Get the futures service status + + https://www.kucoin.com/docs/rest/futures-trading/market-data/get-service-status + + .. code:: python + + currencies = client.futures_get_status() + + :returns: API Response + + .. code-block:: python + { + "status": "open", //open, close, cancelonly + "msg": "upgrade match engine" //remark for operation + } + + """ + return self._get("status", data=params) def get_announcements(self, page=None, limit=None, ann_type=None, lang=None, start=None, end=None, **params): """Get a list of the latest news announcements @@ -4094,7 +4124,7 @@ def get_common_order_data(self, symbol, type, side, size=None, price=None, funds raise KucoinRequestException('Invalid order type {}. Possible types are {} and {}'.format(type, self.ORDER_LIMIT, self.ORDER_MARKET)) if client_oid: - data['clientOid'] = client_oid #todo check if it is mandatory + data['clientOid'] = client_oid if stp: data['stp'] = stp if remark: @@ -5919,6 +5949,8 @@ def hf_get_auto_cancel_order(self, **params): return self._get('hf/orders/dead-cancel-all', True, data=params) + # Stop Orders + def create_stop_order(self, symbol, type, side, stop_price, size=None, price=None, funds=None, client_oid=None, stp=None, remark=None, time_in_force=None, cancel_after=None, post_only=None, hidden=None, iceberg=None, visible_size=None, stop=None, trade_type=None, **params): @@ -6232,6 +6264,8 @@ def get_stop_order_by_client_oid(self, client_oid, symbol=None, **params): return self._get('stop-order/queryOrderByClientOid', True, data=dict(data, **params)) + # OCO Orders + def oco_create_order(self, symbol, side, size, price, stop_price, limit_price, client_oid=None, remark=None, **params): """Create an OCO order @@ -6489,6 +6523,8 @@ def oco_get_orders(self, symbol=None, start=None, end=None, page=None, limit=Non return self._get('oco/orders', True, api_version=self.API_VERSION3, data=dict(data, **params)) + # Margin Orders + def margin_create_order(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, remark=None, time_in_force=None, cancel_after=None, post_only=None, hidden=None, iceberg=None, visible_size=None, margin_model=None, auto_borrow=None, auto_repay=None, **params): @@ -6651,6 +6687,8 @@ def margin_create_test_order(self, symbol, type, side, size=None, price=None, fu return self._post('margin/order/test', True, data=dict(data, **params)) + # HF Margin Orders + def hf_margin_create_order(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, remark=None, time_in_force=None, cancel_after=None, post_only=None, hidden=None, iceberg=None, visible_size=None, is_isolated=None, auto_borrow=None, auto_repay=None, **params): @@ -7085,6 +7123,418 @@ def hf_margin_get_symbol_with_active_orders(self, trade_type, **params): return self._get('hf/margin/order/active/symbols', True, api_version=self.API_VERSION3, data=dict(data, **params)) + # Futures Orders + + def get_common_futures_order_data(self, symbol, type=None, side=None, size=None, price=None, funds=None, client_oid=None, + stp=None, remark=None, time_in_force=None, post_only=None, + hidden=None, iceberg=None, visible_size=None, value_qty=None, leverage=None, + stop=None, stop_price_type=None, trigger_stop_up_price=None, stop_price=None, trigger_stop_down_price=None, + reduce_only=None, force_hold=None, margin_mode=None, is_tpsl_order=None, **params): + + data = { + 'symbol': symbol + } + + client_oid = client_oid or params.get('clientOid') + if client_oid: + data['clientOid'] = client_oid + else: + data['clientOid'] = flat_uuid() + + if type: + data['type'] = type + else: + raise KucoinRequestException('type is required for futures orders') + + if side: + data['side'] = side + else: + raise KucoinRequestException('side is required for futures orders') + + if leverage: + data['leverage'] = leverage + else: + raise KucoinRequestException('leverage is required for futures orders') + + funds = funds or params.get('qty') + value_qty = value_qty or params.get('valueQty') + if size: + if funds or value_qty: + raise KucoinRequestException('size cannot be used with funds or value_qty') + data['size'] = size + elif funds: + if size or value_qty: + raise KucoinRequestException('funds cannot be used with size or value_qty') + data['qty'] = funds + elif value_qty: + if size or funds: + raise KucoinRequestException('value_qty cannot be used with size or funds') + data['valueQty'] = value_qty + else: + raise KucoinRequestException('size, funds or value_qty is required for futures orders') + + if type == self.ORDER_MARKET: + if price: + raise MarketOrderException('Cannot use price parameter with market order') + if time_in_force: + raise MarketOrderException('Cannot use time_in_force parameter with market order') + if post_only: + raise MarketOrderException('Cannot use post_only parameter with market order') + if hidden: + raise MarketOrderException('Cannot use hidden parameter with market order') + if iceberg: + raise MarketOrderException('Cannot use iceberg parameter with market order') + if visible_size: + raise MarketOrderException('Cannot use visible_size parameter with market order') + elif type == self.ORDER_LIMIT: + if not price: + raise LimitOrderException('Price is required for limit order') + if hidden and iceberg: + raise LimitOrderException('Order can be either "hidden" or "iceberg"') + if iceberg and not visible_size: + raise LimitOrderException('Iceberg order requires visible_size') + data['price'] = price + if time_in_force: + data['timeInForce'] = time_in_force + if post_only: + data['postOnly'] = post_only + if hidden: + data['hidden'] = hidden + if iceberg: + data['iceberg'] = iceberg + if visible_size: + data['visibleSize'] = visible_size + + if stp: + data['stp'] = stp + if remark: + data['remark'] = remark + if reduce_only: + data['reduceOnly'] = reduce_only + if force_hold: + data['forceHold'] = force_hold + if margin_mode: + data['marginMode'] = margin_mode + + if is_tpsl_order: + if trigger_stop_up_price: + data['triggerStopUpPrice'] = trigger_stop_up_price + if stop_price_type: + data['stopPriceType'] = stop_price_type + if trigger_stop_down_price: + data['triggerStopDownPrice'] = trigger_stop_down_price + else: + if stop: + if (not stop_price_type) or (not stop_price): + raise KucoinRequestException('stop_price_type and stop_price are required for stop orders') + data['stop'] = stop + data['stopPriceType'] = stop_price_type + data['stopPrice'] = stop_price + + return data + + + def futures_create_order(self, symbol, type=None, side=None, size=None, price=None, funds=None, client_oid=None, + stp=None, remark=None, time_in_force=None, post_only=None, + hidden=None, iceberg=None, visible_size=None, value_qty=None, leverage=None, + stop=None, stop_price_type=None, stop_price=None, reduce_only=None, close_order=None, + force_hold=None, margin_mode=None, **params): + """Create a futures order + + https://www.kucoin.com/docs/rest/futures-trading/orders/place-order + + :param symbol: Name of symbol e.g. ETHUSDTM + :type symbol: string + :param type: (optional)order type - limit or market (default is limit) + Is mandatory if close_order!=True + :type type: string + :param side: (optional) buy or sell + Is mandatory if close_order!=True + :type side: string + :param size: (optional) Desired amount in base currency + Is mandatory if funds and value_qty are not passed and close_order!=True + :type size: string + :param price: (optional) Price per base currency + Is mandatory for limit order + :type price: string + :param funds: (optional) Desired amount of quote currency to use + Is mandatory if size and value_qty are not passed and close_order!=True + :type funds: string + :param client_oid: (optional) Unique order id (default flat_uuid()) + :type client_oid: string + :param stp: (optional) self trade protection CN, CO or CB (default is None). DC is not supported + :type stp: string + :param remark: (optional) remark for the order, max 100 utf8 characters + :type remark: string + :param time_in_force: (optional) GTC or IOC - default is GTC + :type time_in_force: string + :param post_only: (optional) Post only flag (default is False) + :type post_only: bool + :param hidden: (optional) Hidden order flag (default is False) + :type hidden: bool + :param iceberg: (optional) Iceberg order flag (default is False) + :type iceberg: bool + :param visible_size: (optional) The maximum visible size of an iceberg order + :type visible_size: string + :param value_qty: (optional) Order size (Value), USDS-Swap correspond to USDT or USDC. + The unit of the quantity of coin-swap is size(lot), which is not supported + Is mandatory if size and funds are not passed and close_order!=True + :type value_qty: string + :param leverage: (optional) Leverage of the order + is mandatory if close_order!=True + :type leverage: string + :param stop: (optional) down or up. Requires stopPrice and stopPriceType to be defined + :type stop: string + :param stop_price_type: (optional) Either TP (trade price), IP (index price) or MP (mark price) + Is mandatory if stop is defined + :type stop_price_type: string + :param stop_price: (optional) The trigger price of the order + Is mandatory if stop is defined + :type stop_price: string + :param reduce_only: (optional) Reduce only flag (default is False) + :type reduce_only: bool + :param close_order: (optional) A flag to close the position. Set to false by default. + If closeOrder is set to True, the system will close the position and the position size will become 0. + Side, Size and Leverage fields can be left empty and the system will determine the side and size automatically. + :type close_order: bool + :param force_hold: (optional) A flag to forcely hold the funds for an order, even though it's an order to reduce the position size. + This helps the order stay on the order book and not get canceled when the position size changes. + Set to false by default. The system will forcely freeze certain amount of funds for this order, including orders whose direction is opposite to the current positions. + This feature is to ensure that the order would not be canceled by the matching engine in such a circumstance that not enough funds are frozen for the order. + :type force_hold: bool + :param margin_mode: (optional) ISOLATED or CROSS (default is ISOLATED) + :type margin_mode: string + + .. code:: python + + order = client.futures_create_order('ETHUSDTM', type=Client.ORDER_LIMIT, side=Client.SIDE_BUY, size=20, price=2000) + order = client.futures_create_order('ETHUSDTM', type=Client.ORDER_MARKET, side=Client.SIDE_BUY, funds=20) + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException, MarketOrderException, LimitOrderException, KucoinRequestException + + """ + + if close_order: + data = { + 'symbol': symbol, + } + else: + data = self.get_common_futures_order_data(symbol, type=type, side=side, size=size, price=price, funds=funds, + client_oid=client_oid, stp=stp, remark=remark, time_in_force=time_in_force, + post_only=post_only, hidden=hidden, iceberg=iceberg, + visible_size=visible_size, value_qty=value_qty, leverage=leverage, + stop=stop, stop_price_type=stop_price_type, stop_price=stop_price, + reduce_only=reduce_only, force_hold=force_hold, margin_mode=margin_mode, + is_tpsl_order=False, **params) + + return self._post('orders', True, is_futures=True, data=dict(data, **params)) + + def futures_create_test_order(self, symbol, type=None, side=None, size=None, price=None, funds=None, client_oid=None, + stp=None, remark=None, time_in_force=None, post_only=None, + hidden=None, iceberg=None, visible_size=None, value_qty=None, leverage=None, + stop=None, stop_price_type=None, stop_price=None, reduce_only=None, close_order=None, + force_hold=None, margin_mode=None, **params): + """Create a futures test order + + https://www.kucoin.com/docs/rest/futures-trading/orders/place-order-test + + :param symbol: Name of symbol e.g. ETHUSDTM + :type symbol: string + :param type: (optional)order type - limit or market (default is limit) + Is mandatory if close_order!=True + :type type: string + :param side: (optional) buy or sell + Is mandatory if close_order!=True + :type side: string + :param size: (optional) Desired amount in base currency + Is mandatory if funds and value_qty are not passed and close_order!=True + :type size: string + :param price: (optional) Price per base currency + Is mandatory for limit order + :type price: string + :param funds: (optional) Desired amount of quote currency to use + Is mandatory if size and value_qty are not passed and close_order!=True + :type funds: string + :param client_oid: (optional) Unique order id (default flat_uuid()) + :type client_oid: string + :param stp: (optional) self trade protection CN, CO or CB (default is None). DC is not supported + :type stp: string + :param remark: (optional) remark for the order, max 100 utf8 characters + :type remark: string + :param time_in_force: (optional) GTC or IOC - default is GTC + :type time_in_force: string + :param post_only: (optional) Post only flag (default is False) + :type post_only: bool + :param hidden: (optional) Hidden order flag (default is False) + :type hidden: bool + :param iceberg: (optional) Iceberg order flag (default is False) + :type iceberg: bool + :param visible_size: (optional) The maximum visible size of an iceberg order + :type visible_size: string + :param value_qty: (optional) Order size (Value), USDS-Swap correspond to USDT or USDC. + The unit of the quantity of coin-swap is size(lot), which is not supported + Is mandatory if size and funds are not passed and close_order!=True + :type value_qty: string + :param leverage: (optional) Leverage of the order + is mandatory if close_order!=True + :type leverage: string + :param stop: (optional) down or up. Requires stopPrice and stopPriceType to be defined + :type stop: string + :param stop_price_type: (optional) Either TP (trade price), IP (index price) or MP (mark price) + Is mandatory if stop is defined + :type stop_price_type: string + :param stop_price: (optional) The trigger price of the order + Is mandatory if stop is defined + :type stop_price: string + :param reduce_only: (optional) Reduce only flag (default is False) + :type reduce_only: bool + :param close_order: (optional) A flag to close the position. Set to false by default. + If closeOrder is set to True, the system will close the position and the position size will become 0. + Side, Size and Leverage fields can be left empty and the system will determine the side and size automatically. + :type close_order: bool + :param force_hold: (optional) A flag to forcely hold the funds for an order, even though it's an order to reduce the position size. + This helps the order stay on the order book and not get canceled when the position size changes. + Set to false by default. The system will forcely freeze certain amount of funds for this order, including orders whose direction is opposite to the current positions. + This feature is to ensure that the order would not be canceled by the matching engine in such a circumstance that not enough funds are frozen for the order. + :type force_hold: bool + :param margin_mode: (optional) ISOLATED or CROSS (default is ISOLATED) + :type margin_mode: string + + .. code:: python + + order = client.futures_create_test_order('ETHUSDTM', type=Client.ORDER_LIMIT, side=Client.SIDE_BUY, size=20, price=2000) + order = client.futures_create_test_order('ETHUSDTM', type=Client.ORDER_MARKET, side=Client.SIDE_BUY, funds=20) + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException, MarketOrderException, LimitOrderException, KucoinRequestException + + """ + + if close_order: + data = { + 'symbol': symbol, + } + else: + data = self.get_common_futures_order_data(symbol, type=type, side=side, size=size, price=price, funds=funds, + client_oid=client_oid, stp=stp, remark=remark, time_in_force=time_in_force, + post_only=post_only, hidden=hidden, iceberg=iceberg, + visible_size=visible_size, value_qty=value_qty, leverage=leverage, + stop=stop, stop_price_type=stop_price_type, stop_price=stop_price, + reduce_only=reduce_only, force_hold=force_hold, margin_mode=margin_mode, + is_tpsl_order=False, **params) + + return self._post('orders/test', True, is_futures=True, data=dict(data, **params)) + + def futures_create_stop_order(self, symbol, type=None, side=None, size=None, price=None, funds=None, client_oid=None, + stp=None, remark=None, time_in_force=None, post_only=None, + hidden=None, iceberg=None, visible_size=None, value_qty=None, leverage=None, + trigger_stop_up_price=None, stop_price_type=None, trigger_stop_down_price=None, + reduce_only=None, close_order=None, force_hold=None, margin_mode=None, **params): + """Create a futures take profit and/or stop loss order + + https://www.kucoin.com/docs/rest/futures-trading/orders/place-take-profit-and-stop-loss-order + + :param symbol: Name of symbol e.g. ETHUSDTM + :type symbol: string + :param type: (optional)order type - limit or market (default is limit) + Is mandatory if close_order!=True + :type type: string + :param side: (optional) buy or sell + Is mandatory if close_order!=True + :type side: string + :param size: (optional) Desired amount in base currency + Is mandatory if funds and value_qty are not passed and close_order!=True + :type size: string + :param price: (optional) Price per base currency + Is mandatory for limit order + :type price: string + :param funds: (optional) Desired amount of quote currency to use + Is mandatory if size and value_qty are not passed and close_order!=True + :type funds: string + :param client_oid: (optional) Unique order id (default flat_uuid()) + :type client_oid: string + :param stp: (optional) self trade protection CN, CO or CB (default is None). DC is not supported + :type stp: string + :param remark: (optional) remark for the order, max 100 utf8 characters + :type remark: string + :param time_in_force: (optional) GTC or IOC - default is GTC + :type time_in_force: string + :param post_only: (optional) Post only flag (default is False) + :type post_only: bool + :param hidden: (optional) Hidden order flag (default is False) + :type hidden: bool + :param iceberg: (optional) Iceberg order flag (default is False) + :type iceberg: bool + :param visible_size: (optional) The maximum visible size of an iceberg order + :type visible_size: string + :param value_qty: (optional) Order size (Value), USDS-Swap correspond to USDT or USDC. + The unit of the quantity of coin-swap is size(lot), which is not supported + Is mandatory if size and funds are not passed and close_order!=True + :type value_qty: string + :param leverage: (optional) Leverage of the order + is mandatory if close_order!=True + :type leverage: string + :param trigger_stop_up_price: (optional) The trigger price of the take profit order + :type trigger_stop_up_price: string + :param stop_price_type: (optional) Either TP (trade price), IP (index price) or MP (mark price) + :type stop_price_type: string + :param trigger_stop_down_price: (optional) The trigger price of the stop loss order + :type trigger_stop_down_price: string + :param reduce_only: (optional) Reduce only flag (default is False) + :type reduce_only: bool + :param close_order: (optional) A flag to close the position. Set to false by default. + If closeOrder is set to True, the system will close the position and the position size will become 0. + Side, Size and Leverage fields can be left empty and the system will determine the side and size automatically. + :type close_order: bool + :param force_hold: (optional) A flag to forcely hold the funds for an order, even though it's an order to reduce the position size. + This helps the order stay on the order book and not get canceled when the position size changes. + Set to false by default. The system will forcely freeze certain amount of funds for this order, including orders whose direction is opposite to the current positions. + This feature is to ensure that the order would not be canceled by the matching engine in such a circumstance that not enough funds are frozen for the order. + :type force_hold: bool + :param margin_mode: (optional) ISOLATED or CROSS (default is ISOLATED) + :type margin_mode: string + + .. code:: python + + order = client.futures_create_stop_order('ETHUSDTM', type=Client.ORDER_LIMIT, side=Client.SIDE_BUY, size=20, price=2000) + order = client.futures_create_stop_order('ETHUSDTM', type=Client.ORDER_MARKET, side=Client.SIDE_BUY, funds=20) + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException, MarketOrderException, LimitOrderException, KucoinRequestException + + """ + + if close_order: + data = { + 'symbol': symbol, + } + else: + data = self.get_common_futures_order_data(symbol, type=type, side=side, size=size, price=price, funds=funds, + client_oid=client_oid, stp=stp, remark=remark, time_in_force=time_in_force, + post_only=post_only, hidden=hidden, iceberg=iceberg, + visible_size=visible_size, value_qty=value_qty, leverage=leverage, + trigger_stop_up_price=trigger_stop_up_price, stop_price_type=stop_price_type, + trigger_stop_down_price=trigger_stop_down_price,reduce_only=reduce_only, + force_hold=force_hold, margin_mode=margin_mode, is_tpsl_order=True, **params) + + return self._post('st-orders', True, is_futures=True, data=dict(data, **params)) + # Fill Endpoints def get_fills(self, trade_type, order_id=None, symbol=None, side=None, type=None, start=None, end=None, page=None, limit=None, **params): From e31037fc96dcc885c781ddfbedad8d4703790fcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Wed, 20 Nov 2024 15:41:49 +0300 Subject: [PATCH 58/60] endpoints for futures orders added --- kucoin/client.py | 428 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 418 insertions(+), 10 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 46e8842..0559db5 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -45,11 +45,11 @@ class Client(object): TIMEINFORCE_IMMEDIATE_OR_CANCEL = 'IOC' TIMEINFORCE_FILL_OR_KILL = 'FOK' - SPOT_KC_PARTNER = 'ccxt' # todo handle with standard python-kucoin signature - SPOT_KC_KEY = '9e58cc35-5b5e-4133-92ec-166e3f077cb8' + # SPOT_KC_PARTNER = 'ccxt' # todo handle with standard python-kucoin signature + # SPOT_KC_KEY = '9e58cc35-5b5e-4133-92ec-166e3f077cb8' - # SPOT_KC_PARTNER = 'python-kucoinspot' - # SPOT_KC_KEY = '922783d1-067e-4a31-bb42-4d1589624e30' + SPOT_KC_PARTNER = 'python-kucoinspot' + SPOT_KC_KEY = '922783d1-067e-4a31-bb42-4d1589624e30' def __init__(self, api_key, api_secret, passphrase, sandbox=False, requests_params=None): """Kucoin API Client constructor @@ -7231,7 +7231,7 @@ def get_common_futures_order_data(self, symbol, type=None, side=None, size=None, data['stopPriceType'] = stop_price_type data['stopPrice'] = stop_price - return data + return dict(data, **params) def futures_create_order(self, symbol, type=None, side=None, size=None, price=None, funds=None, client_oid=None, @@ -7283,7 +7283,8 @@ def futures_create_order(self, symbol, type=None, side=None, size=None, price=No :param leverage: (optional) Leverage of the order is mandatory if close_order!=True :type leverage: string - :param stop: (optional) down or up. Requires stopPrice and stopPriceType to be defined + :param stop: (optional) down (triggers when the price reaches or goes below the stopPrice) or up (triggers when the price reaches or goes above the stopPrice). + Requires stopPrice and stopPriceType to be defined :type stop: string :param stop_price_type: (optional) Either TP (trade price), IP (index price) or MP (mark price) Is mandatory if stop is defined @@ -7333,7 +7334,7 @@ def futures_create_order(self, symbol, type=None, side=None, size=None, price=No reduce_only=reduce_only, force_hold=force_hold, margin_mode=margin_mode, is_tpsl_order=False, **params) - return self._post('orders', True, is_futures=True, data=dict(data, **params)) + return self._post('orders', True, is_futures=True, data=data) def futures_create_test_order(self, symbol, type=None, side=None, size=None, price=None, funds=None, client_oid=None, stp=None, remark=None, time_in_force=None, post_only=None, @@ -7384,7 +7385,8 @@ def futures_create_test_order(self, symbol, type=None, side=None, size=None, pri :param leverage: (optional) Leverage of the order is mandatory if close_order!=True :type leverage: string - :param stop: (optional) down or up. Requires stopPrice and stopPriceType to be defined + :param stop: (optional) down (triggers when the price reaches or goes below the stopPrice) or up (triggers when the price reaches or goes above the stopPrice). + Requires stopPrice and stopPriceType to be defined :type stop: string :param stop_price_type: (optional) Either TP (trade price), IP (index price) or MP (mark price) Is mandatory if stop is defined @@ -7434,7 +7436,7 @@ def futures_create_test_order(self, symbol, type=None, side=None, size=None, pri reduce_only=reduce_only, force_hold=force_hold, margin_mode=margin_mode, is_tpsl_order=False, **params) - return self._post('orders/test', True, is_futures=True, data=dict(data, **params)) + return self._post('orders/test', True, is_futures=True, data=data) def futures_create_stop_order(self, symbol, type=None, side=None, size=None, price=None, funds=None, client_oid=None, stp=None, remark=None, time_in_force=None, post_only=None, @@ -7533,7 +7535,413 @@ def futures_create_stop_order(self, symbol, type=None, side=None, size=None, pri trigger_stop_down_price=trigger_stop_down_price,reduce_only=reduce_only, force_hold=force_hold, margin_mode=margin_mode, is_tpsl_order=True, **params) - return self._post('st-orders', True, is_futures=True, data=dict(data, **params)) + return self._post('st-orders', True, is_futures=True, data=data) + + def futures_create_orders(self, orders_data): + """Create multiple futures orders + You can place up to 20 orders at one time, including limit orders, market orders, and stop orders + + https://www.kucoin.com/docs/rest/futures-trading/orders/place-multiple-orders + + :param orders_data: List of orders data + :type orders_data: list + Every order data is a dict with the same parameters as futures_create_order + + .. code:: python + + orders = [ + { + 'symbol': 'ETHUSDTM', + 'type': Client.ORDER_LIMIT, + 'side': Client.SIDE_BUY, + 'size': 20, + 'price': 2000 + }, + { + 'symbol': 'ETHUSDTM', + 'type': Client.ORDER_MARKET, + 'side': Client.SIDE_BUY, + 'funds': 20 + } + ] + order = client.futures_create_orders(orders) + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException, MarketOrderException, LimitOrderException, KucoinRequestException + + """ + + data = [] + for order in orders_data: + if 'close_order' in order and order['close_order']: + data.append({ + 'symbol': order['symbol'], + 'closeOrder': True + }) + else: + order_data = self.get_common_futures_order_data(**order) + del order_data['clientOid'] + data.append(order_data) + + return self._post('orders/multi', True, is_futures=True, data=data) + + def futures_cancel_order(self, order_id, **params): + """Cancel a futures order by order id + + https://www.kucoin.com/docs/rest/futures-trading/orders/cancel-order-by-orderid + + :param order_id: Order id + :type order_id: string + + .. code:: python + + res = client.futures_cancel_order('5bd6e9286d99522a52e458de') + + :returns: ApiResponse + + .. code:: python + + { + "cancelledOrderIds": [ + "5bd6e9286d99522a52e458de" + ] + } + + :raises: KucoinResponseException, KucoinAPIException + + KucoinAPIException If order_id is not found + + """ + + return self._delete('orders/{}'.format(order_id), True, is_futures=True, data=params) + + def futures_cancel_order_by_client_oid(self, client_oid, symbol, **params): + """Cancel a futures order by the clientOid + + https://www.kucoin.com/docs/rest/futures-trading/orders/cancel-order-by-clientoid + + :param client_oid: ClientOid + :type client_oid: string + :param symbol: Name of symbol e.g. KCS-BTC + :type symbol: string + + .. code:: python + + res = client.futures_cancel_order_by_client_oid('6d539dc614db3', 'KCS-BTC') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + KucoinAPIException If order_id is not found + + """ + + data = { + 'symbol': symbol + } + + return self._delete('orders/client-order/{}'.format(client_oid), True, is_futures=True, data=dict(data, **params)) + + def futures_cancel_orders(self, symbol=None, order_ids=None, client_oids=None, **params): + """Cancel multiple futures orders by order ids or clientOids + Either order_ids or client_oids and symbol are mandatory + + https://www.kucoin.com/docs/rest/futures-trading/orders/batch-cancel-orders + + :param symbol: (optional) Name of symbol e.g. ETHUSDTM + Is mandatory if order_ids are not passed + :type symbol: string + :param order_ids: (optional) List of order ids + Is mandatory if client_oids is not passed + :type order_ids: list + :param client_oids: (optional) List of clientOids + Is mandatory if order_ids are not passed + :type client_oids: list + + .. code:: python + + res = client.futures_cancel_orders(['5bd6e9286d99522a52e458de', '5bd6e9286d99522a52e458df']) + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + KucoinAPIException If order_id is not found + + """ + + data = {} + if order_ids and client_oids: + raise KucoinRequestException('Either order_ids or client_oids should be passed, not both') + if not order_ids and not client_oids: + raise KucoinRequestException('Either order_ids or client_oids should be passed') + if order_ids: + data['orderIdsList'] = order_ids + elif not symbol: + raise KucoinRequestException('symbol is required if client_oids are passed') + else: + data['clientOidsList'] = client_oids + data['symbol'] = symbol + + return self._delete('orders/multi-cancel', True, is_futures=True, data=dict(data, **params)) + + def futures_cancel_all_orders(self, symbol=None, **params): + """Cancel all futures orders + + https://www.kucoin.com/docs/rest/futures-trading/orders/cancel-multiple-futures-limit-orders + + :param symbol: (optional) Name of symbol e.g. ETHUSDTM + :type symbol: string + + .. code:: python + + res = client.futures_cancel_all_orders() + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + data = {} + if symbol: + data['symbol'] = symbol + + return self._delete('orders', True, is_futures=True, data=dict(data, **params)) + + def futures_cancel_all_stop_orders(self, symbol=None, **params): + """Cancel all futures stop orders + + https://www.kucoin.com/docs/rest/futures-trading/orders/cancel-multiple-futures-stop-orders + + :param symbol: (optional) Name of symbol e.g. ETHUSDTM + :type symbol: string + + .. code:: python + + res = client.futures_cancel_all_stop_orders() + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + data = {} + if symbol: + data['symbol'] = symbol + + return self._delete('stopOrders', True, is_futures=True, data=dict(data, **params)) + + def futures_get_orders(self, symbol=None, status=None, side=None, order_type=None, + start=None, end=None, page=None, limit=None, **params): + """Get list of futures orders + + https://www.kucoin.com/docs/rest/futures-trading/orders/get-order-list + + :param symbol: (optional) Name of symbol e.g. KCS-BTC + :type symbol: string + :param status: (optional) Specify status active or done (default done) + :type status: string + :param side: (optional) buy or sell + :type side: string + :param order_type: (optional) limit, market, limit_stop or market_stop + :type order_type: string + :param start: (optional) Start time as unix timestamp + :type start: string + :param end: (optional) End time as unix timestamp + :type end: string + :param page: (optional) Page to fetch + :type page: int + :param limit: (optional) Number of orders (default 50, max 1000) + :type limit: int + + .. code:: python + + orders = client.futures_get_orders(symbol='ETHUSDTM', status='active') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + + if symbol: + data['symbol'] = symbol + if status: + data['status'] = status + if side: + data['side'] = side + if order_type: + data['type'] = order_type + if start: + data['startAt'] = start + if end: + data['endAt'] = end + if page: + data['currentPage'] = page + if limit: + data['pageSize'] = limit + + return self._get('orders', True, is_futures=True, data=dict(data, **params)) + + def futures_get_stop_orders(self, symbol=None, side=None, order_type=None, + start=None, end=None, page=None, limit=None, **params): + """Get list of untriggered futures stop orders + + https://www.kucoin.com/docs/rest/futures-trading/orders/get-untriggered-stop-order-list + + :param symbol: (optional) Name of symbol e.g. KCS-BTC + :type symbol: string + :param side: (optional) buy or sell + :type side: string + :param order_type: (optional) limit, market, limit_stop or market_stop + :type order_type: string + :param start: (optional) Start time as unix timestamp + :type start: string + :param end: (optional) End time as unix timestamp + :type end: string + :param page: (optional) Page to fetch + :type page: int + :param limit: (optional) Number of orders (default 50, max 1000) + :type limit: int + + .. code:: python + + orders = client.futures_get_stop_orders(symbol='ETHUSDTM') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + + if symbol: + data['symbol'] = symbol + if side: + data['side'] = side + if order_type: + data['type'] = order_type + if start: + data['startAt'] = start + if end: + data['endAt'] = end + if page: + data['currentPage'] = page + if limit: + data['pageSize'] = limit + + return self._get('stopOrders', True, is_futures=True, data=dict(data, **params)) + + def futures_get_recent_orders(self, symbol=None, **params): + """Get up to 1000 last futures done orders in the last 24 hours. + + https://www.kucoin.com/docs/rest/futures-trading/orders/get-list-of-orders-completed-in-24h + + :param symbol: (optional) Name of symbol e.g. ETHUSDTM + :type symbol: string + + .. code:: python + + orders = client.futures_get_recent_orders() + + :returns: ApiResponse + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + if symbol: + data['symbol'] = symbol + + return self._get('recentDoneOrders', True, is_futures=True, data=dict(data, **params)) + + def futures_get_order(self, order_id, **params): + """Get futures order details by order id + + https://www.kucoin.com/docs/rest/futures-trading/orders/get-order-details-by-orderid-clientoid + + :param order_id: orderOid value + :type order_id: str + + .. code:: python + + order = client.futures_get_order('5c35c02703aa673ceec2a168') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + return self._get('orders/{}'.format(order_id), True, is_futures=True, data=params) + + def futures_get_order_by_client_oid(self, client_oid, **params): + """Get futures order details by clientOid + + https://www.kucoin.com/docs/rest/futures-trading/orders/get-order-details-by-orderid-clientoid + + :param client_oid: clientOid value + :type client_oid: string + + .. code:: python + + order = client.futures_get_order_by_client_oid('6d539dc614db312') + + :returns: ApiResponse + + .. code:: python + + todo add the response example + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'clientOid': client_oid + } + + return self._get('orders/byClientOid', True, is_futures=True, data=params) # Fill Endpoints From c8e16ffe404f19ed8489f079773a07a7a904c14a Mon Sep 17 00:00:00 2001 From: rayBastard Date: Mon, 25 Nov 2024 01:22:47 +0200 Subject: [PATCH 59/60] Futures Position Endpoints added futures_get_max_open_position_size futures_get_positions futures_get_positions_history futures_modify_auto_deposit_margin futures_get_max_withdraw_margin futures_withdraw_margin futures_deposit_margin futures_get_margin_mode futures_modify_margin_mode futures_get_cross_margin_leverage futures_modify_cross_margin_leverage --- kucoin/client.py | 405 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 392 insertions(+), 13 deletions(-) diff --git a/kucoin/client.py b/kucoin/client.py index 0559db5..78e7921 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -274,7 +274,7 @@ def futures_get_status(self, **params): } """ - return self._get("status", data=params) + return self._get("status", is_futures=True, data=params) def get_announcements(self, page=None, limit=None, ann_type=None, lang=None, start=None, end=None, **params): """Get a list of the latest news announcements @@ -2188,7 +2188,7 @@ def futures_get_account_detail(self, currency=None, **params): if currency: data['currency'] = currency - return self._get('account-overview', True, data=dict(data, **params)) + return self._get('account-overview', True, is_futures=True, data=dict(data, **params)) def get_subaccount_balance(self, sub_user_id, include_base_ammount, **params): """Get the account info of a sub-user specified by the subUserId @@ -2445,7 +2445,7 @@ def futures_get_all_subaccounts_balance(self, currency=None, **params): if currency: data['currency'] = currency - return self._get('account-overview-all', True, data=dict(data, **params)) + return self._get('account-overview-all', True, is_futures=True, data=dict(data, **params)) def get_subaccount_api_list(self, sub_name, api_key=None, **params): """Get the API key list of a sub-user @@ -2980,7 +2980,7 @@ def futures_get_account_activity(self, currency=None, type=None, start=None, end if not forward: data['forward'] = False - return self._get('transaction-history', True, dict(data, **params)) + return self._get('transaction-history', True, is_futures=True, data=dict(data, **params)) # Transfer Endpoints @@ -4051,7 +4051,7 @@ def futures_get_trading_pair_fee(self, symbol, **params): 'symbol': symbol } - return self._get('trade-fees', True, data=dict(data, **params)) + return self._get('trade-fees', True, is_futures=True, data=dict(data, **params)) # Order Endpoints @@ -8309,7 +8309,7 @@ def futures_get_fills(self, order_id=None, symbol=None, side=None, type=None, st if limit: data['pageSize'] = limit - return self._get('fills', False, data=dict(data, **params)) + return self._get('fills', False, is_futures=True, data=dict(data, **params)) def futures_get_recent_fills(self, symbol=None, **params): """Get a list of recent futures fills. @@ -8363,7 +8363,7 @@ def futures_get_recent_fills(self, symbol=None, **params): if symbol: data['symbol'] = symbol - return self._get('recentFills', False, data=dict(data, **params)) + return self._get('recentFills', False, is_futures=True, data=dict(data, **params)) def futures_get_active_order_value(self, symbol, **params): """Get the active order value of a symbol @@ -8400,7 +8400,7 @@ def futures_get_active_order_value(self, symbol, **params): 'symbol': symbol } - return self._get('openOrderStatistics', False, data=dict(data, **params)) + return self._get('openOrderStatistics', False, is_futures=True, data=dict(data, **params)) # Margin Info Endpoints @@ -9588,6 +9588,385 @@ def margin_lending_get_subscription_orders(self, currency, status, purchase_orde return self._get('purchase/orders', True, api_version=self.API_VERSION3, data=dict(data, **params)) + # Futures Position Endpoints + + def futures_get_max_open_position_size(self, symbol, price, leverage, **params): + """Get the maximum open position size for a symbol + + https://www.kucoin.com/docs/rest/futures-trading/positions/get-maximum-open-position-size + + :param symbol: Name of symbol e.g. XBTUSDM + :type symbol: string + :param price: Price + :type price: int + :param leverage: Leverage + :type leverage: int + + .. code:: python + + max_open_position_size = client.futures_get_max_open_position_size('XBTUSDM', 10000, 10) + + :returns: ApiResponse + + .. code:: python + + # todo: example response + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol, + 'price': price, + 'leverage': leverage + } + + return self._get('getMaxOpenSize', True, api_version=self.API_VERSION2, is_futures=True, data=dict(data, **params)) + + def futures_get_position(self, symbol, **params): + """Get the position for a symbol + + https://www.kucoin.com/docs/rest/futures-trading/positions/get-position-details + + :param symbol: Name of symbol e.g. XBTUSDM + + .. code:: python + + position = client.get_position('XBTUSDM') + + :returns: ApiResponse + + .. code:: python + + # todo: example response + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('position', True, is_futures=True, data=dict(data, **params)) + + def futures_get_positions(self, currency=None, **params): + """Get the positions + + https://www.kucoin.com/docs/rest/futures-trading/positions/get-position-list + + :param currency: (optional) Currency + :type currency: string + + .. code:: python + + positions = client.get_positions() + + :returns: ApiResponse + + .. code:: python + + # todo: example response + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + + if currency: + data['currency'] = currency + + return self._get('positions', True, is_futures=True, data=dict(data, **params)) + + def futures_get_positions_history(self, symbol=None, start=None, end=None, page=None, limit=None, **params): + """Get the positions history + + https://www.kucoin.com/docs/rest/futures-trading/positions/get-positions-history + + :param symbol: (optional) Name of symbol e.g. XBTUSDM + :type symbol: string + :param start: (optional) Start time as unix timestamp + :type start: int + :param end: (optional) End time as unix timestamp + :type end: int + :param page: (optional) Page number + :type page: int + :param limit: (optional) Number of requests per page, max 200, default 10 + :type limit: int + + .. code:: python + + positions_history = client.get_positions_history() + + :returns: ApiResponse + + .. code:: python + + # todo: example response + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = {} + + if symbol: + data['symbol'] = symbol + if start: + data['from'] = start + if end: + data['to'] = end + if page: + data['pageId'] = page + if limit: + data['limit'] = limit + + return self._get('history-positions', True, is_futures=True, data=dict(data, **params)) + + def futures_modify_auto_deposit_margin(self, symbol, status=True, **params): + """Modify the auto deposit margin status for a symbol + + https://www.kucoin.com/docs/rest/futures-trading/positions/modify-auto-deposit-margin-status + + :param symbol: Name of symbol e.g. XBTUSDM + :type symbol: string + :param status: Status + :type status: bool + + .. code:: python + + auto_deposit_margin = client.modify_auto_deposit_margin('XBTUSDM', True) + + :returns: ApiResponse + + .. code:: python + + # todo: example response + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol, + 'status': status + } + + return self._post('position/margin/auto-deposit-status', True, is_futures=True, data=dict(data, **params)) + + def futures_get_max_withdraw_margin(self, symbol, **params): + """Get the maximum withdraw margin for a symbol + + https://www.kucoin.com/docs/rest/futures-trading/positions/get-max-withdraw-margin + + :param symbol: Name of symbol e.g. XBTUSDM + :type symbol: string + + .. code:: python + + max_withdraw_margin = client.get_max_withdraw_margin('XBTUSDM') + + :returns: ApiResponse + + .. code:: python + + # todo: example response + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('margin/maxWithdrawMargin', True, is_futures=True, data=dict(data, **params)) + + def futures_withdraw_margin(self, symbol, amount, **params): + """Withdraw margin for a symbol + + https://www.kucoin.com/docs/rest/futures-trading/positions/remove-margin-manually + + :param symbol: Name of symbol e.g. XBTUSDM + :type symbol: string + :param amount: Amount to withdraw + :type amount: string + + .. code:: python + + withdraw_margin = client.withdraw_margin('XBTUSDM', '100') + + :returns: ApiResponse + + .. code:: python + + # todo: example response + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol, + 'amount': amount + } + + return self._post('margin/withdrawMargin', True, is_futures=True, data=dict(data, **params)) + + def futures_deposit_margin(self, symbol, margin, biz_no, **params): + """Deposit margin for a symbol + + https://www.kucoin.com/docs/rest/futures-trading/positions/add-margin-manually + + :param symbol: Name of symbol e.g. XBTUSDM + :type symbol: string + :param margin: Margin + :type margin: int + :param biz_no: Business number + :type biz_no: string + + .. code:: python + + deposit_margin = client.deposit_margin('XBTUSDM', 100, '123456') + + :returns: ApiResponse + + .. code:: python + + # todo: example response + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol, + 'margin': margin, + 'bizNo': biz_no + } + + return self._post('position/margin/deposit-margin', True, is_futures=True, data=dict(data, **params)) + + def futures_get_margin_mode(self, symbol, **params): + """Get the margin mode for a symbol + + https://www.kucoin.com/docs/rest/futures-trading/positions/get-margin-mode + + :param symbol: Name of symbol e.g. XBTUSDM + :type symbol: string + + .. code:: python + + margin_mode = client.get_margin_mode('XBTUSDM') + + :returns: ApiResponse + + .. code:: python + + # todo: example response + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('position/getMarginMode', True, api_version=self.API_VERSION2, is_futures=True, data=dict(data, **params)) + + def futures_modify_margin_mode(self, symbol, mode, **params): + """Modify the margin mode for a symbol + + https://www.kucoin.com/docs/rest/futures-trading/positions/modify-margin-mode + + :param symbol: Name of symbol e.g. XBTUSDM + :type symbol: string + :param mode: Margin mode (CROSS or ISOLATED) + :type mode: string + + .. code:: python + + margin_mode = client.modify_margin_mode('XBTUSDM', 'CROSS') + + :returns: ApiResponse + + .. code:: python + + # todo: example response + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol, + 'marginMode': mode + } + + return self._post('position/changeMarginMode', True, api_version=self.API_VERSION2, is_futures=True, data=dict(data, **params)) + + def futures_get_cross_margin_leverage(self, symbol, **params): + """Get the cross margin leverage for a symbol + + https://www.kucoin.com/docs/rest/futures-trading/positions/get-cross-margin-leverage + + :param symbol: Name of symbol e.g. XBTUSDM + :type symbol: string + + .. code:: python + + cross_margin_leverage = client.get_cross_margin_leverage('XBTUSDM') + + :returns: ApiResponse + + .. code:: python + + # todo: example response + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol + } + + return self._get('getCrossUserLeverage', True, api_version=self.API_VERSION2, is_futures=True, data=dict(data, **params)) + + def futures_modify_cross_margin_leverage(self, symbol, leverage, **params): + """Modify the cross margin leverage for a symbol + + https://www.kucoin.com/docs/rest/futures-trading/positions/modify-cross-margin-leverage + + :param symbol: Name of symbol e.g. XBTUSDM + :type symbol: string + :param leverage: Leverage + :type leverage: string + + .. code:: python + + cross_margin_leverage = client.modify_cross_margin_leverage('XBTUSDM', '10') + + :returns: ApiResponse + + .. code:: python + + # todo: example response + + :raises: KucoinResponseException, KucoinAPIException + + """ + + data = { + 'symbol': symbol, + 'leverage': leverage + } + + return self._post('changeCrossUserLeverage', True, api_version=self.API_VERSION2, is_futures=True, data=dict(data, **params)) + # Futures Risk Limit Endpoints def futures_get_risk_limit_level(self, symbol, **params): @@ -9636,7 +10015,7 @@ def futures_get_risk_limit_level(self, symbol, **params): 'symbol': symbol } - return self._get('contracts/risk-limit{}'.format(symbol), True, data=dict(data, **params)) + return self._get('contracts/risk-limit{}'.format(symbol), True, is_futures=True, data=dict(data, **params)) def futures_modify_risk_limit_level(self, symbol, level, **params): """Modify the risk limit level for a symbol @@ -9668,7 +10047,7 @@ def futures_modify_risk_limit_level(self, symbol, level, **params): 'level': level } - return self._post('position/risk-limit-level/change', True, data=dict(data, **params)) + return self._post('position/risk-limit-level/change', True, is_futures=True, data=dict(data, **params)) # Futures Funding Fees Endpoints @@ -9707,7 +10086,7 @@ def futures_get_funding_rate(self, symbol, **params): 'symbol': symbol } - return self._get('funding-rate/{}/current'.format(symbol), True, data=dict(data, **params)) + return self._get('funding-rate/{}/current'.format(symbol), True, is_futures=True, data=dict(data, **params)) def futures_get_public_funding_history(self, symbol, start, end, **params): """Get the public funding history for a symbol @@ -9751,7 +10130,7 @@ def futures_get_public_funding_history(self, symbol, start, end, **params): 'to': end } - return self._get('contract/funding-rates', False, data=dict(data, **params)) + return self._get('contract/funding-rates', False, is_futures=True, data=dict(data, **params)) def futures_get_private_funding_history(self, symbol, start=None, end=None, reverse=True, offset=None, forward=False, max_count=None, **params): @@ -9840,7 +10219,7 @@ def futures_get_private_funding_history(self, symbol, start=None, end=None, reve if max_count: data['maxCount'] = max_count - return self._get('funding-history', True, data=dict(data, **params)) + return self._get('funding-history', True, is_futures=True, data=dict(data, **params)) # Websocket Endpoints From b896027a9a9fcd27a9534a4bf1f332975213aa8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9?= Date: Tue, 26 Nov 2024 15:34:37 +0300 Subject: [PATCH 60/60] generate_async_client.js added --- generate_async_client.js | 65 ++++++++++++++++++++++++++++++++++++++++ kucoin/client.py | 40 ++++++++++++------------- 2 files changed, 85 insertions(+), 20 deletions(-) create mode 100644 generate_async_client.js diff --git a/generate_async_client.js b/generate_async_client.js new file mode 100644 index 0000000..c32b6cf --- /dev/null +++ b/generate_async_client.js @@ -0,0 +1,65 @@ +const fs = require ('fs') +const SOURSE_FILE_NAME = './kucoin/client.py' +const TARGET_FILE_NAME = './kucoin/async_client_generated.py' +const REQUESTS = ['_get', '_post', '_put', '_delete', '_request'] +const METHOD_DEFINITION_MATCH = /def\s(\w+)/ +const METHOD_CALL_MATCH = /self\.(\w+)\(/ +const DEFINITION_PREFIX = 'def' +const ASYNC_DEFINITION_PREFIX = 'async def' +const CALL_PREFIX = 'self.' +const ASYNC_CALL_PREFIX = 'await self.' +const ASYNC_CLIENT_TEMPLATE = 'import asyncio' +const SPECIAL_REPLACEMENTS = {} // Add special replacements here +const SPECIAL_REPLACEMENTS_KEYS = Object.keys (SPECIAL_REPLACEMENTS) + +function replaceKeywords (data) { + const lines = data.split ('\n') + const asyncClient = [ ASYNC_CLIENT_TEMPLATE ] + for (let line of lines) { + let specialMatch = false + for (let key of SPECIAL_REPLACEMENTS_KEYS) { + if (line.includes (key)) { + asyncClient.push (line.replace (key, SPECIAL_REPLACEMENTS[key])) + delete SPECIAL_REPLACEMENTS[key] + specialMatch = true + break + } + } + if (specialMatch) { + continue + } + const methodDefinition = line.match (METHOD_DEFINITION_MATCH) + const methodCall = line.match (METHOD_CALL_MATCH) + const match = methodDefinition || methodCall + if (match) { + const methodName = match[1] + let replacementRequired = true + if (methodName.startsWith ('_') && !REQUESTS.includes (methodName)) { + replacementRequired = false + } + if (replacementRequired) { + if (methodDefinition) { + line = line.replace (DEFINITION_PREFIX, ASYNC_DEFINITION_PREFIX) + } else if (methodCall) { + line = line.replace (CALL_PREFIX, ASYNC_CALL_PREFIX) + } + } + } + asyncClient.push (line) + } + return asyncClient.join ('\n') +} + +fs.readFile (SOURSE_FILE_NAME, 'utf8', (err, data) => { + if (err) { + console.error (err) + return + } + const asyncClient = replaceKeywords (data) + fs.writeFile (TARGET_FILE_NAME, asyncClient, (err) => { + if (err) { + console.error (err) + return + } + console.log (TARGET_FILE_NAME + ' file is generated')}) + }) \ No newline at end of file diff --git a/kucoin/client.py b/kucoin/client.py index 78e7921..9d4bda0 100644 --- a/kucoin/client.py +++ b/kucoin/client.py @@ -2612,7 +2612,7 @@ def modify_subaccount_api(self, sub_name, api_key, passphrase, permission=None, if expire: data['expire'] = expire - return self._put('sub/api-key/update', True, data=dict(data, **params)) + return self._post('sub/api-key/update', True, data=dict(data, **params)) def delete_subaccount_api(self, api_key, passphrase, sub_name, **params): """Delete Spot APIs for sub-accounts @@ -4055,7 +4055,7 @@ def futures_get_trading_pair_fee(self, symbol, **params): # Order Endpoints - def get_common_order_data(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, + def _get_common_order_data(self, symbol, type, side, size=None, price=None, funds=None, client_oid=None, stp=None, remark=None, time_in_force=None, cancel_after=None, post_only=None, hidden=None, iceberg=None, visible_size=None): """Internal helper for creating a common data for order""" @@ -4197,7 +4197,7 @@ def create_order(self, symbol, type, side, size=None, price=None, funds=None, cl if not client_oid: client_oid = flat_uuid() - data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, + data = self._get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) return self._post('orders', True, data=dict(data, **params)) @@ -4369,7 +4369,7 @@ def create_test_order(self, symbol, type, side, size=None, price=None, funds=Non if not client_oid: client_oid = flat_uuid() - data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, + data = self._get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) return self._post('orders/test', True, data=dict(data, **params)) @@ -4463,7 +4463,7 @@ def create_orders(self, symbol, order_list, **params): for order in order_list: if 'type' in order and order['type'] != self.ORDER_LIMIT: raise KucoinRequestException('Only limit orders are supported by create_orders') - order_data = self.get_common_order_data(symbol, self.ORDER_LIMIT, order['side'], order['size'], order['price'], + order_data = self._get_common_order_data(symbol, self.ORDER_LIMIT, order['side'], order['size'], order['price'], client_oid=order.get('client_oid'), remark=order.get('remark'), stp=order.get('stp'), time_in_force=order.get('time_in_force'), cancel_after=order.get('cancel_after'), post_only=order.get('post_only'), @@ -4902,7 +4902,7 @@ def hf_create_order(self, symbol, type, side, size=None, price=None, funds=None, """ - data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, + data = self._get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) if tags: @@ -5081,7 +5081,7 @@ def hf_create_test_order(self, symbol, type, side, size=None, price=None, funds= """ - data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, + data = self._get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) if tags: @@ -5162,7 +5162,7 @@ def sync_hf_create_order(self, symbol, type, side, size=None, price=None, funds= """ - data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, + data = self._get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) if tags: @@ -5229,7 +5229,7 @@ def hf_create_orders(self, order_list, **params): orders = [] for order in order_list: - order_data = self.get_common_order_data(order.get('symbol'), order.get('type'), order.get('side'), + order_data = self._get_common_order_data(order.get('symbol'), order.get('type'), order.get('side'), order.get('size'), order.get('price'), order.get('funds'), order.get('client_oid'), order.get('stp'), order.get('remark'), order.get('time_in_force'), order.get('cancel_after'), order.get('post_only'), @@ -5306,7 +5306,7 @@ def sync_hf_create_orders(self, order_list, **params): orders = [] for order in order_list: - order_data = self.get_common_order_data(order.get('symbol'), order.get('type'), order.get('side'), + order_data = self._get_common_order_data(order.get('symbol'), order.get('type'), order.get('side'), order.get('size'), order.get('price'), order.get('funds'), order.get('client_oid'), order.get('stp'), order.get('remark'), order.get('time_in_force'), order.get('cancel_after'), order.get('post_only'), @@ -6019,7 +6019,7 @@ def create_stop_order(self, symbol, type, side, stop_price, size=None, price=Non if not client_oid: client_oid = flat_uuid() - data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, + data = self._get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) data['stopPrice'] = stop_price @@ -6592,7 +6592,7 @@ def margin_create_order(self, symbol, type, side, size=None, price=None, funds=N if not client_oid: client_oid = flat_uuid() - data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, + data = self._get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) if margin_model: @@ -6673,7 +6673,7 @@ def margin_create_test_order(self, symbol, type, side, size=None, price=None, fu if not client_oid: client_oid = flat_uuid() - data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, + data = self._get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) if margin_model: @@ -6756,7 +6756,7 @@ def hf_margin_create_order(self, symbol, type, side, size=None, price=None, fund if not client_oid: client_oid = flat_uuid() - data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, + data = self._get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) if is_isolated: @@ -6835,7 +6835,7 @@ def hf_margin_create_test_order(self, symbol, type, side, size=None, price=None, if not client_oid: client_oid = flat_uuid() - data = self.get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, + data = self._get_common_order_data(symbol, type, side, size, price, funds, client_oid, stp, remark, time_in_force, cancel_after, post_only, hidden, iceberg, visible_size) if is_isolated: @@ -7125,7 +7125,7 @@ def hf_margin_get_symbol_with_active_orders(self, trade_type, **params): # Futures Orders - def get_common_futures_order_data(self, symbol, type=None, side=None, size=None, price=None, funds=None, client_oid=None, + def _get_common_futures_order_data(self, symbol, type=None, side=None, size=None, price=None, funds=None, client_oid=None, stp=None, remark=None, time_in_force=None, post_only=None, hidden=None, iceberg=None, visible_size=None, value_qty=None, leverage=None, stop=None, stop_price_type=None, trigger_stop_up_price=None, stop_price=None, trigger_stop_down_price=None, @@ -7326,7 +7326,7 @@ def futures_create_order(self, symbol, type=None, side=None, size=None, price=No 'symbol': symbol, } else: - data = self.get_common_futures_order_data(symbol, type=type, side=side, size=size, price=price, funds=funds, + data = self._get_common_futures_order_data(symbol, type=type, side=side, size=size, price=price, funds=funds, client_oid=client_oid, stp=stp, remark=remark, time_in_force=time_in_force, post_only=post_only, hidden=hidden, iceberg=iceberg, visible_size=visible_size, value_qty=value_qty, leverage=leverage, @@ -7428,7 +7428,7 @@ def futures_create_test_order(self, symbol, type=None, side=None, size=None, pri 'symbol': symbol, } else: - data = self.get_common_futures_order_data(symbol, type=type, side=side, size=size, price=price, funds=funds, + data = self._get_common_futures_order_data(symbol, type=type, side=side, size=size, price=price, funds=funds, client_oid=client_oid, stp=stp, remark=remark, time_in_force=time_in_force, post_only=post_only, hidden=hidden, iceberg=iceberg, visible_size=visible_size, value_qty=value_qty, leverage=leverage, @@ -7527,7 +7527,7 @@ def futures_create_stop_order(self, symbol, type=None, side=None, size=None, pri 'symbol': symbol, } else: - data = self.get_common_futures_order_data(symbol, type=type, side=side, size=size, price=price, funds=funds, + data = self._get_common_futures_order_data(symbol, type=type, side=side, size=size, price=price, funds=funds, client_oid=client_oid, stp=stp, remark=remark, time_in_force=time_in_force, post_only=post_only, hidden=hidden, iceberg=iceberg, visible_size=visible_size, value_qty=value_qty, leverage=leverage, @@ -7584,7 +7584,7 @@ def futures_create_orders(self, orders_data): 'closeOrder': True }) else: - order_data = self.get_common_futures_order_data(**order) + order_data = self._get_common_futures_order_data(**order) del order_data['clientOid'] data.append(order_data)