-
Notifications
You must be signed in to change notification settings - Fork 1
/
c_api.py
168 lines (122 loc) · 5.42 KB
/
c_api.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
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
import requests
import json
import time
from c_constants import (
coins_list_json_file, coins_json_file, coingecko_headers,
coingecko_currencies_url, coingecko_coins_url, coingecko_markets_url, request_timeout
)
def _do_request(url, params=None):
try:
response = requests.get(
url=url, headers=coingecko_headers, params=params if params else {}, timeout=request_timeout
)
except requests.exceptions.ReadTimeout:
print(f' timeout: {url}\n')
exit()
else:
try:
response_json = response.json()
except Exception as e:
# except json.decoder.JSONDecodeError:
# print(response.content, e.msg)
print(f' bad response from {url}\n')
else:
return response_json
return None
def is_valid_currency(currency):
if currency.lower() == 'usd':
return True
currencies = requests.get(coingecko_currencies_url, headers=coingecko_headers).json()
return True if currency.lower() in currencies else False
def get_coins_list(debug=False, update=False):
if debug:
start = time.perf_counter()
download_list = False
coins_file_str = f'{time.strftime("%H:%M:%S")} coins file ("{coins_list_json_file}")'
if coins_list_json_file.is_file():
if update:
if debug:
print(f' {coins_file_str} found but downloading fresh copy... ', end='', flush=True)
download_list = True
else:
if debug:
print(f' {coins_file_str} found, loading... ', end='', flush=True)
with coins_list_json_file.open() as f:
coins_list = json.load(f)
else:
if debug:
print(f' {coins_file_str} not found, downloading... ', end='', flush=True)
download_list = True
if download_list:
coins_list = requests.get(coingecko_coins_url, headers=coingecko_headers, timeout=request_timeout).json()
with coins_list_json_file.open('w') as f:
json.dump(coins_list, f)
if debug:
print(f'done ({time.perf_counter() - start:,.3f}s)')
return coins_list
def get_coin_prices(coins, currency, debug=False, test=False):
def get_coin_dict():
return {
'rank': coin_data['market_cap_rank'],
'name': coin_data['name'],
'symbol': coin_data['symbol'].upper(),
'price': coin_data['current_price'],
'market_cap': coin_data['market_cap']
}
if debug:
start = time.perf_counter()
update_saved_data = False
if test and coins_json_file.is_file():
if debug:
print(
f' {time.strftime("%H:%M:%S")} price data file ("{coins_json_file}") found, loading... ',
end='', flush=True
)
with coins_json_file.open() as f:
price_data = json.load(f)
else:
if debug:
print(f' {time.strftime("%H:%M:%S")} downloading fresh price data... ', end='', flush=True)
coin_ids = list(set(list(coins['holdings'].keys()) + list(coins['comparison'].keys())))
params = {'ids': ','.join(coin_ids), 'vs_currency': currency}
price_data = _do_request(url=coingecko_markets_url, params=params)
if price_data:
update_saved_data = True
elif coins_json_file.is_file():
print(f' {time.strftime("%H:%M:%S")} no json returned, loading data from "{coins_json_file}"... ')
if debug:
print(
f' {time.strftime("%H:%M:%S")} price data file ("{coins_json_file}") found, loading... ',
end='', flush=True
)
with coins_json_file.open() as f:
price_data = json.load(f)
else:
print(f' {time.strftime("%H:%M:%S")} bad http response and no saved data file found... exiting.')
exit()
for coin_data in price_data:
if coin_data['id'] in coins['comparison']:
# coins['comparison'][coin_data['id']] = get_coin_dict()
coins['comparison'][coin_data['id']]['rank'] = coin_data['market_cap_rank']
coins['comparison'][coin_data['id']]['name'] = coin_data['name']
coins['comparison'][coin_data['id']]['symbol'] = coin_data['symbol'].upper()
coins['comparison'][coin_data['id']]['price'] = coin_data['current_price']
coins['comparison'][coin_data['id']]['market_cap'] = coin_data['market_cap']
if coin_data['id'] in coins['holdings']:
# coins['holdings'][coin_data['id']] = get_coin_dict()
coins['holdings'][coin_data['id']]['rank'] = coin_data['market_cap_rank']
coins['holdings'][coin_data['id']]['name'] = coin_data['name']
coins['holdings'][coin_data['id']]['symbol'] = coin_data['symbol'].upper()
coins['holdings'][coin_data['id']]['price'] = coin_data['current_price']
coins['holdings'][coin_data['id']]['market_cap'] = coin_data['market_cap']
if debug:
print(f'done ({time.perf_counter() - start:,.3f}s)')
if update_saved_data:
if debug:
start = time.perf_counter()
print(f' {time.strftime("%H:%M:%S")} saving fresh price data ("{coins_json_file}")... ', end='', flush=True)
with coins_json_file.open('w') as f:
json.dump(price_data, f)
if debug:
print(f'done ({time.perf_counter() - start:,.3f}s)')
return coins