diff options
Diffstat (limited to 'btcdashboard/pulltoredis.py')
| -rw-r--r-- | btcdashboard/pulltoredis.py | 56 |
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 @@ +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()) |
