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 @@ | |||
| 1 | import asyncio | ||
| 2 | import aiohttp | ||
| 3 | import redis | ||
| 4 | import json | ||
| 5 | import logging | ||
| 6 | import time | ||
| 7 | |||
| 8 | logging.basicConfig(level=logging.INFO) | ||
| 9 | logger = logging.getLogger(__name__) | ||
| 10 | |||
| 11 | # redis default port | ||
| 12 | redis_client = redis.Redis(host='localhost', port=6379, db=0) | ||
| 13 | |||
| 14 | URL = 'https://api.kraken.com/0/public/Ticker?pair=BTCUSD' | ||
| 15 | HEADERS = {'Accept': 'application/json'} | ||
| 16 | |||
| 17 | MAX_PRICES = 10 | ||
| 18 | UPDATE_INTERVAL = 3 # seconds | ||
| 19 | |||
| 20 | async 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 | |||
| 29 | async 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 | |||
| 51 | async def main(): | ||
| 52 | logger.info("btc price update") | ||
| 53 | await update_price() | ||
| 54 | |||
| 55 | if __name__ == "__main__": | ||
| 56 | asyncio.run(main()) | ||
