blob: 0a82fa70f5b51ea0adb3f725760b4828362c7d78 (
plain)
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
|
import asyncio
import aiohttp
import redis
import json
import logging
import time
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# redis default port
redis_client = redis.Redis(host='localhost', port=6379, db=0)
URL = 'https://api.kraken.com/0/public/Ticker?pair=BTCUSD'
HEADERS = {'Accept': 'application/json'}
MAX_PRICES = 10
UPDATE_INTERVAL = 3 # seconds
async def fetch_btc_price(session):
try:
async with session.get(URL, headers=HEADERS, ssl=False) as response:
data = await response.json()
return float(data['result']['XXBTZUSD']['c'][0])
except Exception as e:
logger.error(f"error getting price: {e}")
return None
async def update_price():
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
while True:
price = await fetch_btc_price(session)
if price:
timestamp = int(time.time()) # this is unix
price_data = json.dumps({"price": price, "timestamp": timestamp})
redis_client.lpush('btc_prices', price_data)
redis_client.ltrim('btc_prices', 0, MAX_PRICES - 1)
logger.info(f"updated btc price: ${price}")
all_prices = redis_client.lrange('btc_prices', 0, -1)
logger.info("prices:")
for i, p in enumerate(all_prices, 1):
p_data = json.loads(p)
logger.info(f"{i}. ${p_data['price']} at {p_data['timestamp']}")
await asyncio.sleep(UPDATE_INTERVAL)
async def main():
logger.info("btc price update")
await update_price()
if __name__ == "__main__":
asyncio.run(main())
|