-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoingecko.py
55 lines (51 loc) · 1.56 KB
/
coingecko.py
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
import requests
from constants import HEADER, REQUEST_TIMEOUT
from typing import Optional
def get_token_price_in_usd(token_id: str) -> Optional[float]:
"""
Returns the Coingecko price in usd of the given token.
"""
#token_id = "gnosis"
coingecko_url = (
"https://api.coingecko.com/api/v3/coins/"
+ token_id
)
try:
coingecko_data = requests.get(
coingecko_url,
headers=HEADER,
timeout=REQUEST_TIMEOUT,
)
coingecko_rsp = coingecko_data.json()
coingecko_price_in_usd = float(coingecko_rsp["market_data"]["current_price"]["usd"])
except requests.RequestException as err:
print("Failed to fetch price")
return None
return coingecko_price_in_usd
def get_historical_token_price(
token_id: str, currency: str = "usd"
) -> list[list[float]]:
"""
Returns the hourly historic Coingecko price in usd of the given token by id.
COW is "cow-protocol", WETH is "ethereum"
"""
coingecko_url = (
"https://api.coingecko.com/api/v3/coins/"
+ token_id
+ "/market_chart?vs_currency="
+ currency
+ "&days=14"
)
try:
coingecko_data = requests.get(
coingecko_url,
timeout=REQUEST_TIMEOUT,
)
coingecko_rsp = coingecko_data.json()
prices = [
{"time": int(p[0] / 1000), "price": p[1]} for p in coingecko_rsp["prices"]
]
except requests.RequestException as err:
print("Failed to fetch price")
raise error
return prices