summaryrefslogtreecommitdiff
path: root/btcdashboard/pulltoredis.py
diff options
context:
space:
mode:
Diffstat (limited to 'btcdashboard/pulltoredis.py')
-rw-r--r--btcdashboard/pulltoredis.py56
1 files changed, 56 insertions, 0 deletions
diff --git a/btcdashboard/pulltoredis.py b/btcdashboard/pulltoredis.py
new file mode 100644
index 0000000..0a82fa7
--- /dev/null
+++ b/btcdashboard/pulltoredis.py
@@ -0,0 +1,56 @@
1import asyncio
2import aiohttp
3import redis
4import json
5import logging
6import time
7
8logging.basicConfig(level=logging.INFO)
9logger = logging.getLogger(__name__)
10
11# redis default port
12redis_client = redis.Redis(host='localhost', port=6379, db=0)
13
14URL = 'https://api.kraken.com/0/public/Ticker?pair=BTCUSD'
15HEADERS = {'Accept': 'application/json'}
16
17MAX_PRICES = 10
18UPDATE_INTERVAL = 3 # seconds
19
20async def fetch_btc_price(session):
21 try:
22 async with session.get(URL, headers=HEADERS, ssl=False) as response:
23 data = await response.json()
24 return float(data['result']['XXBTZUSD']['c'][0])
25 except Exception as e:
26 logger.error(f"error getting price: {e}")
27 return None
28
29async def update_price():
30 async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
31 while True:
32 price = await fetch_btc_price(session)
33 if price:
34 timestamp = int(time.time()) # this is unix
35 price_data = json.dumps({"price": price, "timestamp": timestamp})
36
37 redis_client.lpush('btc_prices', price_data)
38
39 redis_client.ltrim('btc_prices', 0, MAX_PRICES - 1)
40
41 logger.info(f"updated btc price: ${price}")
42
43 all_prices = redis_client.lrange('btc_prices', 0, -1)
44 logger.info("prices:")
45 for i, p in enumerate(all_prices, 1):
46 p_data = json.loads(p)
47 logger.info(f"{i}. ${p_data['price']} at {p_data['timestamp']}")
48
49 await asyncio.sleep(UPDATE_INTERVAL)
50
51async def main():
52 logger.info("btc price update")
53 await update_price()
54
55if __name__ == "__main__":
56 asyncio.run(main())