From 1935560b4051702b558921b19327cfeba903afbe Mon Sep 17 00:00:00 2001 From: kalzu Date: Tue, 20 Dec 2022 17:20:40 +0200 Subject: [PATCH] some kraken_fetch.py devoplemnt, its now runs in background thread! --- btc_tracker/kraken_fetch.py | 52 +++++++++++++++++++++++++------------ 1 file changed, 36 insertions(+), 16 deletions(-) diff --git a/btc_tracker/kraken_fetch.py b/btc_tracker/kraken_fetch.py index 3188259..72cbac4 100755 --- a/btc_tracker/kraken_fetch.py +++ b/btc_tracker/kraken_fetch.py @@ -2,7 +2,8 @@ import krakenex import json, sqlite3 -import requests, os +import requests, os, time +import threading database = "btc_ohlc.db" @@ -155,8 +156,8 @@ def fetch_gemini(): print(f"Error fetching data from Gemini API: {response.status_code}") return "Gemini: ERROR" -def write_dict_to_database(in_dict): - +def write_dict_to_database(in_dict, connection): + cursor = connection.cursor() # Use placeholders for the values in the INSERT statement insert_query = "INSERT INTO ohlc (exchange, timestamp, open, high, low, close, volume_quote, volume_base, trades) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)" @@ -169,21 +170,40 @@ def write_dict_to_database(in_dict): in_dict['volume_quote'], in_dict['volume_base'], in_dict['trades']) - cursor.execute(insert_query, values) - db.commit() + ## apply lock while writing to database + with database_lock: + cursor.execute(insert_query, values) + connection.commit() def get_the_data(): - - write_dict_to_database(json.loads(fetch_kraken())) - write_dict_to_database(json.loads(fetch_bitfinex())) - write_dict_to_database(json.loads(fetch_bitstamp())) - write_dict_to_database(json.loads(fetch_gemini())) - - db.close() + #cursor = db.cursor() + while True: + db = sqlite3.connect(database) + write_dict_to_database(json.loads(fetch_kraken()), db) + write_dict_to_database(json.loads(fetch_bitfinex()), db) + write_dict_to_database(json.loads(fetch_bitstamp()), db) + write_dict_to_database(json.loads(fetch_gemini()), db) + db.close() + time.sleep(290) + Checkthedatabase() -db = sqlite3.connect(database) -cursor = db.cursor() -get_the_data() -exit(0) +database_lock = threading.Lock() +# make this run in thread and allow contium to http api stuff +fetch_thread = threading.Thread(target=get_the_data) +fetch_thread.daemon = True +fetch_thread.start() + +db = sqlite3.connect(database) +count = 1 +while True: + if count % 10 == 0: + print("------- status ", count, "-------") + top2_rows = db.execute("SELECT * FROM ohlc LIMIT 2").fetchall() + print(json.dumps(top2_rows, indent=4)) + else: + output = str(count) + ".. " + print(output, end = '\r') + count = count + 1 + time.sleep(30)