E-Paper-Calendar/Calendar/GeckoCrypto.py

63 lines
2 KiB
Python
Raw Normal View History

2019-05-19 00:22:24 +02:00
from CryptoInterface import CryptoInterface
from datetime import datetime
from CryptoCoin import CryptoCoin
from urllib.request import urlopen
import json
import math
2019-05-19 22:05:49 +02:00
api_test_url = "https://api.coingecko.com/api/v3/ping"
2019-05-19 00:22:24 +02:00
api_url = "https://api.coingecko.com/api/v3/"
api_metadata_url = api_url + "coins/list"
api_price_url = api_url + "simple/price"
price_currency = "usd"
price_currency_sign = "$"
class GeckoCrypto(CryptoInterface):
def __init__(self, coins):
2019-05-19 22:08:14 +02:00
self.coin_ids = coins
2019-05-19 00:22:24 +02:00
self.metadata = None
super(GeckoCrypto, self).__init__()
def is_available(self):
try:
urlopen(api_test_url)
return True
except:
return False
def __get_coins__(self):
self.__prepare_metadata__()
coins = []
2019-05-19 22:08:14 +02:00
for id in self.coin_ids:
2019-05-19 00:22:24 +02:00
try:
2019-05-19 22:08:14 +02:00
data = urlopen(api_price_url + "?include_24hr_change=true&ids=" + self.metadata[id]['id'] + "&vs_currencies=" + price_currency).read()
2019-05-19 00:22:24 +02:00
dataJSON = json.loads(data.decode('utf-8'))
2019-05-19 22:08:14 +02:00
raw = dataJSON[id][price_currency]
2019-05-19 00:22:24 +02:00
price = math.ceil(raw*100) / 100
2019-05-19 22:08:14 +02:00
change = dataJSON[id]['usd_24h_change']
2019-05-19 00:22:24 +02:00
2019-05-19 22:08:14 +02:00
coins.append(self.__build_coin__(id, price, change))
2019-05-19 00:22:24 +02:00
except:
2019-05-19 22:08:14 +02:00
print("Gecko-Error [" + id + "]")
2019-05-19 00:22:24 +02:00
return coins
2019-05-19 22:08:14 +02:00
def __build_coin__(self, id, value, change):
2019-05-19 00:22:24 +02:00
coin = CryptoCoin()
2019-05-19 22:08:14 +02:00
coin.name = self.metadata[id]['name']
2019-05-19 00:22:24 +02:00
coin.day_change = round(change, 2)
coin.price = value
coin.datetime = datetime.now()
coin.fetch_datetime = datetime.now()
coin.currency = price_currency_sign
2019-05-19 22:08:14 +02:00
coin.symbol = self.metadata[id]['symbol']
2019-05-19 00:22:24 +02:00
return coin
def __prepare_metadata__(self):
self.metadata = None
data = urlopen(api_metadata_url).read()
dataJSON = json.loads(data.decode('utf-8'))
2019-05-19 22:08:14 +02:00
self.metadata = { coin['id'].lower() : coin for coin in dataJSON if coin['id'].lower() in self.coin_ids }