File size: 12,966 Bytes
9c400b9 383415a 9c400b9 6a7abb7 9c400b9 383415a 6a7abb7 383415a 9c400b9 6a7abb7 a3ce5eb 9c400b9 383415a 9c400b9 6a7abb7 9c400b9 383415a 9c400b9 d068566 9c400b9 383415a 9c400b9 d068566 383415a 6a7abb7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 |
import os
from dotenv import load_dotenv
load_dotenv()
import httpx
from enum import Enum
from src.libs.logger import logger
from src.databases.redis import REDIS_CACHED
from src.libs.helper_functions import convert_to_snakecase
from src.libs.constants import (
ONE_HOUR_IN_SECONDS,
ONE_MONTH_IN_SECONDS,
ONE_MINUTE_IN_SECONDS,
ONE_QUARTER_IN_SECONDS,
CRYPTO_COMPARE_API_BASE_URL,
CRYPTO_COMPARE_ASSET_DATA_API_BASE_URL,
)
redis_cache = REDIS_CACHED
class CryptoCompareNewsSortOrder(Enum):
LATEST = "latest"
POPULAR = "popular"
def __str__(self):
return self.value
class CryptoCompareLanguages(Enum):
English = "EN"
French = "FR"
Espanol = "ES"
Turkish = "TR"
Portuguese = "PT"
def __str__(self):
return self.value
class CryptoCompare:
def __init__(self, base_url: str = None, asset_data_base_url: str = None) -> None:
self.CRYPTO_COMPARE_API_BASE_URL = base_url or CRYPTO_COMPARE_API_BASE_URL
self.CRYPTO_COMPARE_ASSET_DATA_API_BASE_URL = asset_data_base_url or CRYPTO_COMPARE_ASSET_DATA_API_BASE_URL
# @redis_cache(ttl=ONE_MINUTE_IN_SECONDS)
@logger.instrument()
def get_all_coins(self) -> dict:
url = f"{self.CRYPTO_COMPARE_API_BASE_URL}data/all/coinlist"
logger.debug(url)
params = {"api_key": os.getenv("CRYPTOCOMPARE_API_KEY")}
logger.debug(params)
headers = {"Content-type":"application/json; charset=UTF-8"}
logger.debug(headers)
try:
with httpx.Client(timeout=30.0) as client:
response = client.get(url, params=params, headers=headers)
response.raise_for_status() # Raise an exception if the request was unsuccessful
return convert_to_snakecase(response.json())
except httpx.HTTPError as e:
print(f"An error occurred while making the request: {e}")
return None
@redis_cache(ttl=ONE_MINUTE_IN_SECONDS)
@logger.instrument()
def get_coin_price(self, ids: list[str], vs_currencies: list[str], cache_ttl: int = None) -> dict:
url = f"{self.CRYPTO_COMPARE_API_BASE_URL}data/pricemulti"
# logger.debug(url)
params = {
"api_key": os.getenv("CRYPTOCOMPARE_API_KEY"),
"fsyms": ",".join(ids),
"tsyms": ",".join(vs_currencies)
}
# logger.debug(f"{params}")
headers = {"Content-type":"application/json; charset=UTF-8"}
# logger.debug(f"{headers}")
try:
with httpx.Client(timeout=30.0) as client:
response = client.get(url, params=params, headers=headers)
response.raise_for_status() # Raise an exception if the request was unsuccessful
return response.json()
except httpx.HTTPError as e:
# logger.debug(f"An error occurred while making the request: {e}")
print(f"An error occurred while making the request: {e}")
return None
@redis_cache(ttl=ONE_QUARTER_IN_SECONDS)
@logger.instrument()
def get_overall_coin_data(self, symbol: str, cache_ttl: int = None) -> dict:
url = f"{self.CRYPTO_COMPARE_ASSET_DATA_API_BASE_URL}data/by/symbol"
logger.debug(f"Query URL: {url}")
params = {
"api_key": os.getenv("CRYPTOCOMPARE_API_KEY"),
"asset_symbol": symbol,
}
logger.debug(f"Query params: {params}")
headers = {"Content-type":"application/json; charset=UTF-8"}
logger.debug(f"Query headers {headers}")
try:
with httpx.Client(timeout=30.0) as client:
response = client.get(url, params=params, headers=headers)
response.raise_for_status() # Raise an exception if the request was unsuccessful
return response.json()
except httpx.HTTPError as e:
logger.debug(f"An error occurred while making the request: {e}")
# print(f"An error occurred while making the request: {e}")
return None
@redis_cache(ttl=ONE_QUARTER_IN_SECONDS)
@logger.instrument()
def get_news_categories(self, cache_ttl: int = None) -> dict:
"""
Retrieves the news categories from the CryptoCompare API.
Args:
cache_ttl (int, optional): The time-to-live (TTL) for the cached response. Defaults to None.
Returns:
dict: A dictionary containing the news categories from the CryptoCompare API.
Raises:
httpx.HTTPError: If an error occurs while making the request to the CryptoCompare API.
"""
url = f"{self.CRYPTO_COMPARE_API_BASE_URL}data/news/categories"
logger.debug(f"Query URL: {url}")
params = {
"api_key": os.getenv("CRYPTOCOMPARE_API_KEY"),
}
logger.debug(f"Query params: {params}")
headers = {"Content-type":"application/json; charset=UTF-8"}
logger.debug(f"Query headers {headers}")
try:
with httpx.Client(timeout=30.0) as client:
response = client.get(url, params=params, headers=headers)
response.raise_for_status() # Raise an exception if the request was unsuccessful
return response.json()
except httpx.HTTPError as e:
logger.debug(f"An error occurred while making the request: {e}")
# print(f"An error occurred while making the request: {e}")
return None
@redis_cache(ttl=ONE_HOUR_IN_SECONDS)
@logger.instrument()
def get_latest_news_articles(
self,
language: CryptoCompareLanguages = CryptoCompareLanguages.English,
sort_order: CryptoCompareNewsSortOrder = CryptoCompareNewsSortOrder.LATEST,
cache_ttl: int = None
) -> dict:
"""
Retrieves the latest news articles from the CryptoCompare API.
Args:
language (CryptoCompareLanguages, optional): The language of the news articles. Defaults to English.
sort_order (CryptoCompareNewsSortOrder, optional): The sort order of the news articles. Defaults to 'latest'.
cache_ttl (int, optional): The time-to-live (TTL) for the cached response. Defaults to None.
Returns:
dict: A dictionary containing the latest news articles from the CryptoCompare API.
Raises:
httpx.HTTPError: If an error occurs while making the request to the CryptoCompare API.
Example:
# Get the latest news articles in English, sorted by popularity
latest_news = crypto_compare_instance.get_latest_news_articles(language=CryptoCompareLanguages.English, sort_order=CryptoCompareNewsSortOrder.POPULAR)
"""
url = f"{self.CRYPTO_COMPARE_API_BASE_URL}data/v2/news/"
logger.debug(f"Query URL: {url}")
params = {
"api_key": os.getenv("CRYPTOCOMPARE_API_KEY"),
"lang": language,
"sortOrder": sort_order,
}
logger.debug(f"Query params: {params}")
headers = {"Content-type":"application/json; charset=UTF-8"}
logger.debug(f"Query headers {headers}")
try:
with httpx.Client(timeout=30.0) as client:
response = client.get(url, params=params, headers=headers)
response.raise_for_status() # Raise an exception if the request was unsuccessful
return response.json()
except httpx.HTTPError as e:
logger.debug(f"An error occurred while making the request: {e}")
# print(f"An error occurred while making the request: {e}")
return None
@redis_cache(ttl=ONE_MONTH_IN_SECONDS)
@logger.instrument()
def get_all_exchanges_general_info(self, cache_ttl: int = None) -> dict:
"""
Retrieves general information about all supported exchanges from the CryptoCompare API.
Args:
cache_ttl (int, optional): The time-to-live (TTL) for the cached response. Defaults to None.
Returns:
dict: A dictionary containing general information about all supported exchanges from the CryptoCompare API.
Raises:
httpx.HTTPError: If an error occurs while making the request to the CryptoCompare API.
Example:
# Get general information about all supported exchanges
all_exchanges_info = crypto_compare_instance.get_all_exchanges_general_info()
"""
url = f"{self.CRYPTO_COMPARE_API_BASE_URL}data/exchanges/general"
logger.debug(f"Query URL: {url}")
params = {
"api_key": os.getenv("CRYPTOCOMPARE_API_KEY"),
}
logger.debug(f"Query params: {params}")
headers = {"Content-type":"application/json; charset=UTF-8"}
logger.debug(f"Query headers {headers}")
try:
with httpx.Client(timeout=30.0) as client:
response = client.get(url, params=params, headers=headers)
response.raise_for_status() # Raise an exception if the request was unsuccessful
return response.json()
except httpx.HTTPError as e:
logger.debug(f"An error occurred while making the request: {e}")
# print(f"An error occurred while making the request: {e}")
return None
@redis_cache(ttl=ONE_MONTH_IN_SECONDS)
@logger.instrument()
def get_all_wallets_general_info(self, cache_ttl: int = None) -> dict:
"""
Retrieves general information about all supported wallets from the CryptoCompare API.
Args:
cache_ttl (int, optional): The time-to-live (TTL) for the cached response. Defaults to None.
Returns:
dict: A dictionary containing general information about all supported wallets from the CryptoCompare API.
Raises:
httpx.HTTPError: If an error occurs while making the request to the CryptoCompare API.
Example:
# Get general information about all supported wallets
all_wallets_info = crypto_compare_instance.get_all_wallets_general_info()
"""
url = f"{self.CRYPTO_COMPARE_API_BASE_URL}data/wallets/general"
logger.debug(f"Query URL: {url}")
params = {
"api_key": os.getenv("CRYPTOCOMPARE_API_KEY"),
}
logger.debug(f"Query params: {params}")
headers = {"Content-type":"application/json; charset=UTF-8"}
logger.debug(f"Query headers {headers}")
try:
with httpx.Client(timeout=30.0) as client:
response = client.get(url, params=params, headers=headers)
response.raise_for_status() # Raise an exception if the request was unsuccessful
return response.json()
except httpx.HTTPError as e:
logger.debug(f"An error occurred while making the request: {e}")
# print(f"An error occurred while making the request: {e}")
return None
# @redis_cache(ttl=ONE_MONTH_IN_SECONDS)
@logger.instrument()
def get_top_tier_exchanges_list(
self,
top_tier: bool = False,
cache_ttl: int = None
) -> dict:
"""
Retrieves a list of top-tier exchanges from the CryptoCompare API.
Args:
top_tier (bool, optional): A boolean flag indicating whether to retrieve top-tier exchanges. Defaults to False.
cache_ttl (int, optional): The time-to-live (TTL) for the cached response. Defaults to None.
Returns:
dict: A dictionary containing a list of top-tier exchanges from the CryptoCompare API.
Raises:
httpx.HTTPError: If an error occurs while making the request to the CryptoCompare API.
Example:
# Get a list of top-tier exchanges
top_tier_exchanges = crypto_compare_instance.get_top_tier_exchanges_list(top_tier=True)
"""
url = f"{self.CRYPTO_COMPARE_API_BASE_URL}data/v4/all/exchanges"
logger.debug(f"Query URL: {url}")
params = {
"api_key": os.getenv("CRYPTOCOMPARE_API_KEY"),
"topTier": 'true' if top_tier else 'false',
}
logger.debug(f"Query params: {params}")
headers = {"Content-type":"application/json; charset=UTF-8"}
logger.debug(f"Query headers {headers}")
try:
with httpx.Client(timeout=30.0) as client:
response = client.get(url, params=params, headers=headers)
response.raise_for_status() # Raise an exception if the request was unsuccessful
return response.json()
except httpx.HTTPError as e:
logger.debug(f"An error occurred while making the request: {e}")
# print(f"An error occurred while making the request: {e}")
return None
|