-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapis.py
More file actions
60 lines (45 loc) · 2.03 KB
/
apis.py
File metadata and controls
60 lines (45 loc) · 2.03 KB
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
import datetime
from abc import ABC, abstractmethod
import logging
import ratelimit
import requests
from backoff import on_exception, expo
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
class MercadoBitcoinApi(ABC):
def __init__(self, coin: str) -> None:
self.coin = coin
self.base_endpoint = "https://www.mercadobitcoin.net/api"
@abstractmethod
def _get_endpoint(self, **kwargs) -> str:
pass
@on_exception(expo, ratelimit.exception.RateLimitException, max_tries=10)
@ratelimit.limits(calls=29, period=30)
@on_exception(expo, requests.exceptions.HTTPError, max_tries=10)
def get_data(self, **kwargs) -> dict:
endpoint = self._get_endpoint(**kwargs)
logger.info(f"Getting data from endpoint: {endpoint}")
response = requests.get(endpoint)
response.raise_for_status()
return response.json()
class DaySummaryApi(MercadoBitcoinApi):
type = "day-summary"
def _get_endpoint(self, date: datetime.date) -> str:
return f"{self.base_endpoint}/{self.coin}/{self.type}/{date.year}/{date.month}/{date.day}"
class TradesApi(MercadoBitcoinApi):
type = "trades"
def _get_unix_epoch(self, date: datetime.datetime) -> int:
return int(date.timestamp())
def _get_endpoint(self, date_from: datetime.datetime = None, date_to: datetime.datetime = None) -> str:
if date_from and not date_to:
unix_date_from = self._get_unix_epoch(date_from)
endpoint = f'{self.base_endpoint}/{self.coin}/{self.type}/{unix_date_from}'
elif date_from and date_to:
if date_from > date_to:
raise RuntimeError("date_from cannot be greater than date_to")
unix_date_from = self._get_unix_epoch(date_from)
unix_date_to = self._get_unix_epoch(date_to)
endpoint = f'{self.base_endpoint}/{self.coin}/{self.type}/{unix_date_from}/{unix_date_to}'
else:
endpoint = f'{self.base_endpoint}/{self.coin}/{self.type}'
return endpoint