2024-06-20 21:43:45 +00:00
|
|
|
"""See `KucoinDepoFetcher` for documentation."""
|
|
|
|
|
2024-05-29 20:29:15 +00:00
|
|
|
import datetime
|
|
|
|
import logging
|
2024-07-27 01:14:12 +00:00
|
|
|
import time
|
2024-11-27 23:15:57 +00:00
|
|
|
from collections.abc import Iterator
|
2024-05-29 20:29:15 +00:00
|
|
|
from decimal import Decimal
|
|
|
|
|
2024-06-02 14:14:46 +00:00
|
|
|
import fin_defs
|
2024-05-29 20:29:15 +00:00
|
|
|
import kucoin.client
|
2024-11-27 23:45:46 +00:00
|
|
|
from fin_defs import AssetAmount
|
2024-05-29 20:29:15 +00:00
|
|
|
|
2024-11-27 23:45:46 +00:00
|
|
|
from .data import (
|
|
|
|
DepoFetcher,
|
|
|
|
DepoGroup,
|
|
|
|
DepoSingle,
|
|
|
|
DepositDetails,
|
|
|
|
DoubleRegister,
|
|
|
|
TradeOrderDetails,
|
|
|
|
WithdrawalDetails,
|
|
|
|
)
|
2024-05-29 20:29:15 +00:00
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2024-11-01 10:14:22 +00:00
|
|
|
|
2024-09-05 23:35:09 +00:00
|
|
|
def parse_asset_from_ticker(ticker: str) -> fin_defs.Asset:
|
|
|
|
if ticker == 'KCS':
|
|
|
|
return fin_defs.CryptoCurrency('KCS', coingecko_id='kucoin-shares')
|
|
|
|
return fin_defs.WELL_KNOWN_SYMBOLS[ticker]
|
|
|
|
|
2024-11-27 23:45:46 +00:00
|
|
|
|
2024-11-27 23:15:57 +00:00
|
|
|
def order_from_json(order_details: dict):
|
2024-11-27 23:45:46 +00:00
|
|
|
(asset, base_asset) = [
|
|
|
|
parse_asset_from_ticker(a) for a in order_details['symbol'].split('-')
|
|
|
|
]
|
2024-11-27 23:15:57 +00:00
|
|
|
|
|
|
|
# Convert from kucoin results
|
|
|
|
if order_details['side'] == 'buy':
|
|
|
|
input_asset, output_asset = base_asset, asset
|
|
|
|
input_amount_final = Decimal(order_details['dealFunds'])
|
|
|
|
output_amount_final = Decimal(order_details['dealSize'])
|
|
|
|
else:
|
|
|
|
input_asset, output_asset = asset, base_asset
|
|
|
|
output_amount_final = Decimal(order_details['dealFunds'])
|
|
|
|
input_amount_final = Decimal(order_details['dealSize'])
|
|
|
|
|
|
|
|
fee_asset = parse_asset_from_ticker(order_details['feeCurrency'])
|
|
|
|
|
|
|
|
return TradeOrderDetails(
|
|
|
|
input=AssetAmount(input_asset, input_amount_final),
|
|
|
|
output=AssetAmount(output_asset, output_amount_final),
|
|
|
|
fee=AssetAmount(fee_asset, Decimal(order_details['fee'])),
|
|
|
|
executed_time=datetime.datetime.fromtimestamp(
|
|
|
|
order_details['createdAt'] / 1000,
|
|
|
|
tz=datetime.UTC,
|
|
|
|
),
|
|
|
|
order_id=order_details['id'],
|
|
|
|
raw_order_details=order_details,
|
|
|
|
)
|
|
|
|
|
2024-05-29 20:29:15 +00:00
|
|
|
|
2024-07-18 22:22:29 +00:00
|
|
|
class KucoinDepoFetcher(DepoFetcher):
|
|
|
|
"""`Depo` fetcher for [Kucoin](https://www.kucoin.com), the online crypto currency exchange.
|
2024-06-20 21:43:45 +00:00
|
|
|
|
|
|
|
Requirements for use:
|
|
|
|
- Account on [Kucoin](https://www.kucoin.com).
|
|
|
|
- Have performed Know Your Customer (KYC) for your account.
|
|
|
|
- Created API key from [settings menu](https://www.kucoin.com/account/api).
|
2024-07-20 19:54:29 +00:00
|
|
|
API key must have the **General Permission**. Unless you are using the
|
|
|
|
`place_market_order` functionality, the API key **should not have
|
2024-06-20 21:43:45 +00:00
|
|
|
any additional permissions**. Employ principle of least priviledge.
|
2024-07-18 22:55:12 +00:00
|
|
|
- Install [`python-kucoin`](https://python-kucoin.readthedocs.io/en/latest/) library.
|
2024-06-20 21:43:45 +00:00
|
|
|
|
|
|
|
Depository structure: An upper level depo split for each of the
|
|
|
|
sub-accounts (Funding, Trading, Margin, Futures...)
|
|
|
|
"""
|
|
|
|
|
2024-07-20 19:54:29 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
kucoin_key: str,
|
|
|
|
kucoin_secret: str,
|
|
|
|
kucoin_pass: str,
|
|
|
|
allow_trades: bool = False,
|
|
|
|
):
|
2024-07-18 22:22:29 +00:00
|
|
|
self.assert_param('kucoin_key', str, kucoin_key)
|
|
|
|
self.assert_param('kucoin_secret', str, kucoin_secret)
|
|
|
|
self.assert_param('kucoin_pass', str, kucoin_pass)
|
2024-07-20 19:54:29 +00:00
|
|
|
self.allow_trades = allow_trades
|
|
|
|
self.kucoin_client = kucoin.client.Client(
|
2024-05-29 20:29:15 +00:00
|
|
|
kucoin_key,
|
|
|
|
kucoin_secret,
|
|
|
|
kucoin_pass,
|
|
|
|
)
|
|
|
|
|
|
|
|
def get_depo(self) -> DepoGroup:
|
2024-07-18 23:24:59 +00:00
|
|
|
# We would ideally get timestamp from request,
|
|
|
|
# but this is fine for now.
|
2024-05-29 20:29:15 +00:00
|
|
|
now = datetime.datetime.now(tz=datetime.UTC)
|
2024-07-18 23:24:59 +00:00
|
|
|
|
|
|
|
# Assets are spread across account types, but we would like them
|
|
|
|
# clustered into different depos.
|
2024-05-29 20:29:15 +00:00
|
|
|
assets_by_account_type: dict[str, dict[fin_defs.Asset, Decimal]] = {}
|
2024-07-18 23:24:59 +00:00
|
|
|
|
2024-07-20 19:54:29 +00:00
|
|
|
for account_data in self.kucoin_client.get_accounts():
|
2024-09-05 23:35:09 +00:00
|
|
|
asset = parse_asset_from_ticker(account_data['currency'])
|
2024-06-02 14:14:46 +00:00
|
|
|
balance = Decimal(account_data['balance'])
|
2024-06-02 16:33:25 +00:00
|
|
|
assets_for_account_type = assets_by_account_type.setdefault(
|
2024-06-02 15:24:53 +00:00
|
|
|
account_data['type'],
|
|
|
|
{},
|
2024-06-02 14:14:46 +00:00
|
|
|
)
|
|
|
|
assets_for_account_type[asset] = (
|
|
|
|
assets_for_account_type.get(asset, Decimal(0)) + balance
|
|
|
|
)
|
2024-06-02 16:33:25 +00:00
|
|
|
del account_data, asset, balance, assets_for_account_type
|
2024-07-18 23:24:59 +00:00
|
|
|
|
2024-06-02 14:14:46 +00:00
|
|
|
return DepoGroup(
|
|
|
|
'Kucoin',
|
|
|
|
now,
|
|
|
|
[
|
|
|
|
DepoSingle('Kucoin ' + account_type, now, assets)
|
|
|
|
for account_type, assets in assets_by_account_type.items()
|
|
|
|
],
|
|
|
|
)
|
2024-07-20 19:54:29 +00:00
|
|
|
|
|
|
|
def place_market_order(
|
|
|
|
self,
|
2024-11-28 20:51:31 +00:00
|
|
|
input_: fin_defs.AssetAmount,
|
2024-07-20 19:54:29 +00:00
|
|
|
output_asset: fin_defs.Asset,
|
|
|
|
) -> TradeOrderDetails:
|
|
|
|
"""Executes a market order through the Kucoin market.
|
|
|
|
|
|
|
|
Will automatically determine the market based on the input and output
|
|
|
|
assets.
|
|
|
|
|
|
|
|
Requirements:
|
|
|
|
- Fetcher must have been created with `allow_trades=True`.
|
|
|
|
- API key used with fetcher must have **Spot Trading** permissions.
|
|
|
|
- Assets must be on trading account. Assets on funding accounts or
|
|
|
|
other accounts cannot be used.
|
|
|
|
|
|
|
|
Note:
|
2024-11-01 10:30:18 +00:00
|
|
|
- A fee will be paid to Kucoin, with the rate determined by your VIP
|
2024-07-20 19:54:29 +00:00
|
|
|
level and the asset being traded.
|
|
|
|
- The full `input_amount` may not be used. Inspect the resulting
|
|
|
|
`TradeOrderDetails` to see how much of the `input_amount` have been
|
|
|
|
used.
|
|
|
|
|
2024-07-22 20:01:34 +00:00
|
|
|
References:
|
|
|
|
- POST Market Order: <https://www.kucoin.com/docs/rest/spot-trading/orders/place-order>
|
|
|
|
- GET Market Order by id: <https://www.kucoin.com/docs/rest/spot-trading/orders/get-order-details-by-orderid>
|
2024-07-20 19:54:29 +00:00
|
|
|
"""
|
|
|
|
# Check requirements
|
|
|
|
if not self.allow_trades:
|
|
|
|
msg = 'KucoinDepoFetcher.allow_trades is not enabled: Cannot make trades'
|
|
|
|
raise PermissionError(msg)
|
2024-11-01 10:30:18 +00:00
|
|
|
|
2024-11-28 20:51:31 +00:00
|
|
|
if fin_defs.USDT not in [input_.asset, output_asset]:
|
2024-11-01 10:30:18 +00:00
|
|
|
msg = 'Non-USDT Markets are not supported'
|
|
|
|
raise NotImplementedError(msg)
|
2024-07-20 19:54:29 +00:00
|
|
|
|
|
|
|
# Convert arguments to kucoin client arguments
|
2024-11-28 20:51:31 +00:00
|
|
|
if input_.asset == fin_defs.USDT:
|
2024-11-01 10:14:22 +00:00
|
|
|
symbol: str = (
|
2024-11-28 20:51:31 +00:00
|
|
|
f'{output_asset.raw_short_name()}-{input_.asset.raw_short_name()}'
|
2024-11-01 10:14:22 +00:00
|
|
|
)
|
2024-07-20 19:54:29 +00:00
|
|
|
side: str = 'buy'
|
|
|
|
size = None
|
2024-11-28 20:51:31 +00:00
|
|
|
funds = str(input_.amount)
|
2024-07-20 19:54:29 +00:00
|
|
|
else:
|
2024-11-28 20:51:31 +00:00
|
|
|
symbol = f'{input_.asset.raw_short_name()}-{output_asset.raw_short_name()}'
|
2024-07-20 19:54:29 +00:00
|
|
|
side = 'sell'
|
2024-11-28 20:51:31 +00:00
|
|
|
size = str(input_.amount)
|
2024-07-20 19:54:29 +00:00
|
|
|
funds = None
|
|
|
|
|
|
|
|
# Place order
|
|
|
|
logger.info('Placing order: %s', str([symbol, side, size, funds]))
|
|
|
|
response = self.kucoin_client.create_market_order(
|
|
|
|
symbol=symbol,
|
|
|
|
side=side,
|
|
|
|
size=size,
|
|
|
|
funds=funds,
|
|
|
|
)
|
2024-11-28 20:51:31 +00:00
|
|
|
del symbol, side, size, funds, input_
|
2024-07-20 19:54:29 +00:00
|
|
|
|
|
|
|
# Determine order details
|
2024-11-27 23:15:57 +00:00
|
|
|
return self._get_order_details(response['orderId'])
|
2024-07-22 20:18:17 +00:00
|
|
|
|
2024-11-27 20:56:13 +00:00
|
|
|
def _get_withdrawals(self) -> list[WithdrawalDetails]:
|
|
|
|
raw_details = self.kucoin_client.get_withdrawals()
|
|
|
|
|
|
|
|
withdrawals = []
|
|
|
|
for item in raw_details['items']:
|
|
|
|
withdrawn_asset = parse_asset_from_ticker(item['currency'])
|
|
|
|
withdrawn_amount = Decimal(item['amount'])
|
2024-11-27 23:45:46 +00:00
|
|
|
fee_asset = withdrawn_asset # Assumed
|
2024-11-27 20:56:13 +00:00
|
|
|
fee_amount = Decimal(item['fee'])
|
2024-11-27 23:45:46 +00:00
|
|
|
executed_time = datetime.datetime.fromtimestamp(
|
2024-11-27 20:56:13 +00:00
|
|
|
item['createdAt'] / 1000,
|
|
|
|
tz=datetime.UTC,
|
|
|
|
)
|
|
|
|
|
2024-11-27 23:45:46 +00:00
|
|
|
withdrawals.append(
|
|
|
|
WithdrawalDetails(
|
|
|
|
AssetAmount(withdrawn_asset, withdrawn_amount),
|
|
|
|
AssetAmount(fee_asset, fee_amount),
|
|
|
|
executed_time,
|
|
|
|
item,
|
|
|
|
),
|
|
|
|
)
|
2024-11-27 20:56:13 +00:00
|
|
|
del item
|
|
|
|
|
|
|
|
return withdrawals
|
|
|
|
|
2024-11-27 23:15:57 +00:00
|
|
|
def _get_deposits(self) -> list[DepositDetails]:
|
2024-11-27 20:56:13 +00:00
|
|
|
raw_details = self.kucoin_client.get_deposits()
|
|
|
|
|
|
|
|
deposits = []
|
|
|
|
for item in raw_details['items']:
|
|
|
|
deposit_asset = parse_asset_from_ticker(item['currency'])
|
|
|
|
deposit_amount = Decimal(item['amount'])
|
2024-11-27 23:45:46 +00:00
|
|
|
fee_asset = deposit_asset # Assumed
|
2024-11-27 20:56:13 +00:00
|
|
|
fee_amount = Decimal(item['fee'])
|
2024-11-27 23:45:46 +00:00
|
|
|
executed_time = datetime.datetime.fromtimestamp(
|
2024-11-27 20:56:13 +00:00
|
|
|
item['createdAt'] / 1000,
|
|
|
|
tz=datetime.UTC,
|
|
|
|
)
|
|
|
|
|
2024-11-27 23:45:46 +00:00
|
|
|
deposits.append(
|
|
|
|
DepositDetails(
|
|
|
|
AssetAmount(deposit_asset, deposit_amount),
|
|
|
|
AssetAmount(fee_asset, fee_amount),
|
|
|
|
executed_time,
|
|
|
|
item,
|
|
|
|
),
|
|
|
|
)
|
2024-11-27 20:56:13 +00:00
|
|
|
del item
|
|
|
|
|
|
|
|
return deposits
|
|
|
|
|
2024-11-27 23:15:57 +00:00
|
|
|
def _get_historic_spot_orders(self) -> Iterator[TradeOrderDetails]:
|
|
|
|
end_time = datetime.datetime.now(tz=datetime.UTC)
|
|
|
|
for _weeks_back in range(20):
|
|
|
|
end_time = end_time - datetime.timedelta(days=7)
|
2024-11-27 23:45:46 +00:00
|
|
|
timestamp = int(end_time.timestamp() * 1000)
|
2024-11-27 23:15:57 +00:00
|
|
|
raw_details = self.kucoin_client.get_orders(end=timestamp)
|
|
|
|
yield from (order_from_json(item) for item in raw_details['items'])
|
|
|
|
del _weeks_back, raw_details
|
|
|
|
|
|
|
|
def _get_double_registers(self) -> list[DoubleRegister]:
|
2024-11-29 10:06:43 +00:00
|
|
|
double_registers: list[DoubleRegister] = []
|
|
|
|
double_registers += self._get_deposits()
|
|
|
|
double_registers += self._get_withdrawals()
|
|
|
|
double_registers += self._get_historic_spot_orders()
|
2024-11-27 23:45:46 +00:00
|
|
|
double_registers.sort(key=lambda x: x.executed_time)
|
2024-11-27 23:15:57 +00:00
|
|
|
return double_registers
|
|
|
|
|
2024-07-27 01:14:12 +00:00
|
|
|
def _get_order_details(
|
2024-08-02 05:44:21 +00:00
|
|
|
self,
|
|
|
|
order_id: str,
|
2024-07-27 01:14:12 +00:00
|
|
|
) -> TradeOrderDetails:
|
2024-07-22 20:18:17 +00:00
|
|
|
"""Determine the order details for the order with the given id.
|
|
|
|
|
|
|
|
Retries the order a few times, as KuCoin might not have propagated the
|
|
|
|
order through their systems.
|
|
|
|
"""
|
|
|
|
order_details = self._get_order_with_retries(order_id, num_retries=10)
|
2024-11-27 23:15:57 +00:00
|
|
|
return order_from_json(order_details)
|
2024-07-20 19:54:29 +00:00
|
|
|
|
2024-07-27 01:14:12 +00:00
|
|
|
def _get_order_with_retries(
|
2024-08-02 05:44:21 +00:00
|
|
|
self,
|
|
|
|
order_id: str,
|
|
|
|
*,
|
|
|
|
num_retries: int,
|
|
|
|
sleep_between_tries: float = 1.0,
|
2024-07-27 01:14:12 +00:00
|
|
|
) -> dict:
|
2024-07-22 20:18:17 +00:00
|
|
|
"""Get the order details from KuCoin backend.
|
|
|
|
|
|
|
|
Retries the order a few times, as KuCoin might not have propagated the
|
|
|
|
order through their systems since it was sent.
|
|
|
|
"""
|
|
|
|
for _ in range(num_retries):
|
|
|
|
try:
|
|
|
|
return self.kucoin_client.get_order(order_id)
|
2024-11-01 10:30:18 +00:00
|
|
|
except kucoin.exceptions.KucoinAPIException: # noqa: PERF203
|
2024-07-22 20:18:17 +00:00
|
|
|
time.sleep(sleep_between_tries)
|
|
|
|
return self.kucoin_client.get_order(order_id)
|