From 4b5b93a7d40bcfade7620277e08f6ae2c2cb39b3 Mon Sep 17 00:00:00 2001 From: Thomas Lynch Date: Fri, 27 Sep 2024 21:48:54 +1000 Subject: [PATCH] Add kucoin rates module Move USDT and USDC crypto lists to RateSource base class Update binance module to refer to dicts in RateSource base class --- shkeeper/modules/classes/rate_source.py | 3 +++ shkeeper/modules/rates/binance.py | 11 +++------ shkeeper/modules/rates/kucoin.py | 30 +++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 8 deletions(-) create mode 100644 shkeeper/modules/rates/kucoin.py diff --git a/shkeeper/modules/classes/rate_source.py b/shkeeper/modules/classes/rate_source.py index 98b05c8..d4562fc 100644 --- a/shkeeper/modules/classes/rate_source.py +++ b/shkeeper/modules/classes/rate_source.py @@ -4,6 +4,9 @@ class RateSource(metaclass=ABCMeta): instances = {} + USDT_CRYPTOS = {"USDT", "ETH-USDT", "BNB-USDT", "POLYGON-USDT", "AVALANCHE-USDT"} + USDC_CRYPTOS = {"ETH-USDC", "BNB-USDC", "POLYGON-USDC", "AVALANCHE-USDC"} + def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) instance = cls() diff --git a/shkeeper/modules/rates/binance.py b/shkeeper/modules/rates/binance.py index 6900264..b1982cb 100644 --- a/shkeeper/modules/rates/binance.py +++ b/shkeeper/modules/rates/binance.py @@ -10,20 +10,15 @@ class Binance(RateSource): name = "binance" def get_rate(self, fiat, crypto): - if fiat == "USD" and crypto in { - "USDT", - "ETH-USDT", - "BNB-USDT", - "POLYGON-USDT", - "AVALANCHE-USDT", - }: + if fiat == "USD" and crypto in self.USDT_CRYPTOS: return Decimal(1.0) - if crypto in {"ETH-USDC", "BNB-USDC", "POLYGON-USDC", "AVALANCHE-USDC"}: + if crypto in self.USDC_CRYPTOS: crypto = "USDC" if fiat == "USD": fiat = "USDT" + url = f"https://api.binance.com/api/v3/ticker/price?symbol={crypto}{fiat}" answer = requests.get(url) if answer.status_code == requests.codes.ok: diff --git a/shkeeper/modules/rates/kucoin.py b/shkeeper/modules/rates/kucoin.py new file mode 100644 index 0000000..668bc21 --- /dev/null +++ b/shkeeper/modules/rates/kucoin.py @@ -0,0 +1,30 @@ +import json +from decimal import Decimal + +from shkeeper import requests + +from shkeeper.modules.classes.rate_source import RateSource + + +class KuCoin(RateSource): + name = "kucoin" + + def get_rate(self, fiat, crypto): + if crypto in self.USDT_CRYPTOS: + crypto = "USDT" + + if crypto in self.USDC_CRYPTOS: + crypto = "USDC" + + # https://www.kucoin.com/docs/beginners/introduction + url = f"https://api.kucoin.com/api/v1/prices?base={fiat}¤cies={crypto}" + answer = requests.get(url) + if answer.status_code == requests.codes.ok: + data = json.loads(answer.text) + if data.get("code") == "200000": + #data will be empty dict if symbol doesnt exist even though code is 200000 + price = data.get("data", {}).get(crypto) + if price is not None: + return Decimal(price) + + raise Exception(f"Can't get rate for {crypto} in {fiat}")