-
Notifications
You must be signed in to change notification settings - Fork 2
/
update_close.py
98 lines (83 loc) · 2.99 KB
/
update_close.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
import os
import requests
from decimal import Decimal as dec
from database import (db_session, ExPair, ExPairClose,
IndexPair, IndexPairClose, log)
_exapi_url = os.getenv('EXAPI_URL')
def get_price(exchange, base, quote):
url = f'{_exapi_url}/{exchange}/midprice'
params = {'base': base, 'quote': quote}
r = requests.get(url, params=params)
if r.status_code == 200:
price = r.json()
return dec(price['price_str'])
else:
raise r.status_code
def update_ex_pair_close():
log.debug('Updating ExPairClose')
ex_pairs = ExPair.query.filter_by(active=True).all()
for ex_pair in ex_pairs:
log.debug(f'Updating close for {ex_pair}')
epc = ExPairClose.query.filter_by(
ex_pair_id=ex_pair.id
).first()
try:
close = get_price(ex_pair.exchange.name, ex_pair.base_symbol, ex_pair.quote_symbol)
log.debug(close)
except:
close = 0
if not epc:
epc = ExPairClose(
ex_pair_id=ex_pair.id,
close=close,
)
db_session.add(epc)
db_session.commit()
continue
epc.close = close
log.debug(f'Updated close for {epc}')
db_session.add(epc)
db_session.commit()
log.debug('Finished Updating ExPairClose')
def update_index_pair_close():
log.debug('Updating IndexPairClose')
index_pairs = IndexPair.query.filter_by(active=True).all()
for index_pair in index_pairs:
# Get all related, active and non-External ExPairs
ex_pairs = ExPair.query.filter(
ExPair.quote_currency_id == index_pair.quote_currency_id,
ExPair.base_currency_id == index_pair.base_currency_id,
ExPair.active == True,
).all()
if not ex_pairs:
log.info(f"No exchange pairs available for {index_pair}.")
continue
# Average of exchanges for close
total_close = 0
for ex_pair in ex_pairs:
ex_pair_close = ExPairClose.query.filter_by(ex_pair_id=ex_pair.id).first()
total_close += ex_pair_close[0].close
total_close /= len(ex_pairs)
log.debug(f'Updating close for {index_pair}')
ipc = IndexPairClose.query.filter_by(
ex_pair_id=index_pair.id
).first()
if not ipc:
ipc = IndexPairClose(
ex_pair_id=index_pair.id,
close=total_close,
)
db_session.add(ipc)
db_session.commit()
continue
ipc.close = total_close
log.debug(f'Updated close for {ipc}')
db_session.add(ipc)
db_session.commit()
log.debug('Finished Updating IndexPairClose')
def update_close():
try:
update_ex_pair_close()
update_index_pair_close()
except Exception as e:
log.error(e)