Skip to content
This repository has been archived by the owner on Dec 11, 2024. It is now read-only.

Async HTTP Support #121

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added kucoin/asyncio/__init__.py
Empty file.
Empty file.
123 changes: 123 additions & 0 deletions kucoin/asyncio/async_request/async_request.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
#!/usr/bin/python
# -*- coding:utf-8 -*-

import json
import aiohttp
import hmac
import hashlib
import base64
import time
from uuid import uuid1
from urllib.parse import urljoin


try:
import pkg_resources

version = 'v' + pkg_resources.get_distribution("kucoin-python").version
except (ModuleNotFoundError, pkg_resources.DistributionNotFound, NameError):
version = 'v1.0.0'


class KucoinAsyncRestApi(object):


def __init__(self, key='', secret='', passphrase='', url='', is_v1api=False):
"""
https://docs.kucoin.com

:param key: Api Token Id (Mandatory)
:type key: string
:param secret: Api Secret (Mandatory)
:type secret: string
:param passphrase: Api Passphrase used to create API (Mandatory)
:type passphrase: string
"""

if url:
self.url = url
else:
self.url = 'https://api.kucoin.com'

self.key = key
self.secret = secret
self.passphrase = passphrase
self.is_v1api = is_v1api

async def _request(self, method, uri, timeout=5, auth=True, params=None):
uri_path = uri
data_json = ''
if method in ['GET', 'DELETE']:
if params:
strl = []
for key in sorted(params):
strl.append("{}={}".format(key, params[key]))
data_json += '&'.join(strl)
uri += '?' + data_json
uri_path = uri
else:
if params:
data_json = json.dumps(params)

uri_path = uri + data_json

headers = {}
if auth:
now_time = int(time.time()) * 1000
str_to_sign = str(now_time) + method + uri_path
sign = base64.b64encode(
hmac.new(self.secret.encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha256).digest())
if self.is_v1api:
headers = {
"KC-API-SIGN": sign.decode('utf-8'),
"KC-API-TIMESTAMP": str(now_time),
"KC-API-KEY": self.key,
"KC-API-PASSPHRASE": self.passphrase,
"Content-Type": "application/json"
}
else:
passphrase = base64.b64encode(
hmac.new(self.secret.encode('utf-8'), self.passphrase.encode('utf-8'), hashlib.sha256).digest())
headers = {
"KC-API-SIGN": sign.decode('utf-8'),
"KC-API-TIMESTAMP": str(now_time),
"KC-API-KEY": self.key,
"KC-API-PASSPHRASE": passphrase.decode('utf-8'),
"Content-Type": "application/json",
"KC-API-KEY-VERSION": "2"
}
headers["User-Agent"] = "kucoin-python-sdk/" + version
url = urljoin(self.url, uri)

async with aiohttp.ClientSession() as session:
async with session.request(
method,
url,
headers=headers,
data=data_json if method not in ['GET', 'DELETE'] else None,
timeout=timeout
) as response:
return await self.check_response_data(response)

@staticmethod
async def check_response_data(response):
if response.status == 200:
try:
data = await response.json()
except ValueError:
error_text = await response.text()
raise Exception(f"JSON decoding error: {error_text}")
else:
if data and data.get('code'):
if data.get('code') == '200000':
return data.get('data', data)
else:
message = data.get('message', response.text())
raise Exception(f"API error {data.get('code')}: {message}")
else:
error_text = await response.text()
raise Exception(f"HTTP error {response.status}: {error_text}")

@property
def return_unique_id(self):
return ''.join([each for each in str(uuid1()).split('-')])
31 changes: 31 additions & 0 deletions kucoin/asyncio/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from kucoin.asyncio.earn.earn import AsyncEarnData
from kucoin.asyncio.lending.lending import AsyncLendingData
from kucoin.asyncio.margin.margin import AsyncMarginData
from kucoin.asyncio.market.market import AsyncMarketData
from kucoin.asyncio.trade.trade import AsyncTradeData
from kucoin.asyncio.user.user import AsyncUserData


class User(AsyncUserData):
pass


class Trade(AsyncTradeData):
pass


class Market(AsyncMarketData):
pass


class Lending(AsyncLendingData):
pass

class Earn(AsyncEarnData):
pass


class Margin(AsyncMarginData):
pass


Empty file added kucoin/asyncio/earn/__init__.py
Empty file.
117 changes: 117 additions & 0 deletions kucoin/asyncio/earn/earn.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
from kucoin.asyncio.async_request.async_request import KucoinAsyncRestApi
import warnings


class AsyncEarnData(KucoinAsyncRestApi):

async def subscribe_to_earn_fixed_income_products(self, productId, amount, accountType):
"""
Subscribe to Earn Fixed Income Products
see: https://www.kucoin.com/zh-hant/docs/rest/earn/general/subscribe-to-earn-fixed-income-products
"""
params = {
'productId': productId,
'amount': amount,
'accountType': accountType,
}
return await self._request('POST', '/api/v1/earn/orders', params=params)

async def redeem_by_earn_holding_id(self, orderId, amount, fromAccountType=None, confirmPunishRedeem=None):
"""
Redeem by Earn Holding ID
see: https://www.kucoin.com/zh-hant/docs/rest/earn/general/subscribe-to-earn-fixed-income-products
"""
params = {
'orderId': orderId,
'amount': amount,
}
if fromAccountType:
params['fromAccountType'] = fromAccountType
if confirmPunishRedeem:
params['confirmPunishRedeem'] = confirmPunishRedeem

return await self._request('DELETE', '/api/v1/earn/orders', params=params)

async def get_earn_redeem_preview_by_holding_id(self, orderId, fromAccountType=None):
"""
Get Earn Redeem Preview by Holding ID
see https://www.kucoin.com/docs/rest/earn/general/get-earn-redeem-preview-by-holding-id
"""
params = {
'orderId': orderId,
}
if fromAccountType:
params['fromAccountType'] = fromAccountType
return await self._request('GET', '/api/v1/earn/redeem-preview', params=params)

async def get_earn_savings_products(self, currency=None):
"""
Get Earn Savings Products
see https://www.kucoin.com/docs/rest/earn/kucoin-earn/get-earn-savings-products
"""
params = {
'currency': currency,
}
params = {k: v for k, v in params.items() if v is not None}
return await self._request('GET', '/api/v1/earn/saving/products', params=params)

async def get_earn_fixed_income_current_holdings(self, currentPage=None, pageSize=None, productId=None, productCategory=None, currency=None):
"""
Get Earn Fixed Income Current Holdings
see https://www.kucoin.com/docs/rest/earn/kucoin-earn/get-earn-fixed-income-current-holdings
"""
params = {
'currentPage': currentPage,
'pageSize': pageSize,
'productId': productId,
'productCategory': productCategory,
'currency': currency
}
params = {k: v for k, v in params.items() if v is not None}

return await self._request('GET', '/api/v1/earn/hold-assets', params=params)

async def get_earn_limited_time_promotion_products(self, currency=None):
"""
Get Earn Limited-Time Promotion Products

see https://www.kucoin.com/docs/rest/earn/kucoin-earn/get-earn-limited-time-promotion-products
"""
params = {
'currency': currency
}
params = {k: v for k, v in params.items() if v is not None}

return await self._request('GET', '/api/v1/earn/promotion/products', params=params)

async def get_earn_kcs_staking_products(self, currency=None):
"""
Get Earn KCS Staking Products
see https://www.kucoin.com/docs/rest/earn/staking/get-earn-kcs-staking-products
"""
params = {
'currency': currency
}
params = {k: v for k, v in params.items() if v is not None}

return await self._request('GET', '/api/v1/earn/kcs-staking/products', params=params)

async def get_earn_staking_products(self, currency=None):
"""
Get Earn Staking Products
see https://www.kucoin.com/docs/rest/earn/staking/get-earn-staking-products
"""
params = {
'currency': currency
}
params = {k: v for k, v in params.items() if v is not None}

return await self._request('GET', '/api/v1/earn/staking/products', params=params)

async def get_earn_eth_staking_products(self):
"""
Get Earn ETH Staking Products
see https://www.kucoin.com/docs/rest/earn/staking/get-earn-eth-staking-products
"""

return await self._request('GET', '/api/v1/earn/eth-staking/products')
Empty file.
87 changes: 87 additions & 0 deletions kucoin/asyncio/lending/lending.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
from kucoin.asyncio.async_request.async_request import KucoinAsyncRestApi
import warnings


class AsyncLendingData(KucoinAsyncRestApi):

async def get_currency_information(self, currency):
"""
Get Currency Information
see:https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/get-currency-information
"""
params = {
'currency': currency
}
return await self._request('GET', '/api/v3/project/list', params=params)

async def get_interest_rates(self, currency):
"""
Get Interest Rates
see https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/get-interest-rates
"""
params = {
'currency': currency
}
return await self._request('GET', '/api/v3/project/marketInterestRate', params=params)

async def subscription(self, currency, interest_rate, size):
"""
Subscription
see: https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/subscription
"""
params = {
'currency': currency,
'interestRate': interest_rate,
'size': size,
}
return await self._request('POST', '/api/v3/purchase', params=params)

async def redemption(self, currency, purchase_order_no, size):
"""
Redemption
see: https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/redemption
"""
params = {
'currency': currency,
'purchaseOrderNo': purchase_order_no,
'size': size,
}
return await self._request('POST', '/api/v3/redeem', params=params)

async def modify_subscription_orders(self, currency, purchase_order_no, interest_rate):
"""
Modify Subscription Orders
see: https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/modify-subscription-orders
"""
params = {
'currency': currency,
'purchaseOrderNo': purchase_order_no,
'interestRate': interest_rate,
}
return await self._request('POST', '/api/v3/lend/purchase/update', params=params)

async def get_redemption_orders(self, currency,status, **kwargs):
"""
Get Redemption Orders
see https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/get-redemption-orders
"""
params = {
'currency': currency,
'status': status
}
if kwargs:
params.update(kwargs)
return await self._request('GET', '/api/v3/redeem/orders', params=params)

async def get_subscription_orders(self, currency,status, **kwargs):
"""
Get Subscription Orders
see https://www.kucoin.com/docs/rest/margin-trading/lending-market-v3-/get-subscription-orders
"""
params = {
'currency': currency,
'status': status
}
if kwargs:
params.update(kwargs)
return await self._request('GET', '/api/v3/purchase/orders', params=params)
Empty file.
Loading