Compare commits

..

3 Commits

View File

@ -1,14 +1,20 @@
#!/usr/bin/python3 #!/usr/bin/python3
import krakenex import krakenex, math
import json, sqlite3 import json, sqlite3, binascii
import requests, os, time import requests, os, time
import threading import threading, ecdsa
from hashlib import sha256
from flask import Flask, request from flask import Flask, request
database = "btc_ohlc.db" database = "btc_ohlc.db"
app = Flask(__name__) app = Flask(__name__)
## Add your public key here
user_publickeys = {
"kalzu": 'f1debc13fb21fe0eee54525aa4f8aae5733b201c755edaa55f8893c90aa375b261a62eaa3110651ac5d7705d402581256a37508b0a1ca28bd919ea44710d9c88'
}
database_lock = threading.Lock() database_lock = threading.Lock()
# Empty response json # Empty response json
@ -17,7 +23,7 @@ empty_json = json.dumps(empty_dict)
def Checkthedatabase(): def Checkthedatabase():
## Some sanity for the database ## Some sanity for the database
# check if btc_timeseries.db database file exists # check if the database file exists
if not os.path.exists(database): if not os.path.exists(database):
db = sqlite3.connect(database) db = sqlite3.connect(database)
@ -164,10 +170,39 @@ def fetch_gemini():
print(f"Error fetching data from Gemini API: {response.status_code}") print(f"Error fetching data from Gemini API: {response.status_code}")
return empty_json return empty_json
def fetch_bybit():
## BYBIT
#curl 'https://api-testnet.bybit.com/v2/public/kline/list?symbol=BTCUSD&interval=5&from=1672225349&limit=3'
base_url = 'https://api.bybit.com/v2/public/kline/list?symbol=BTCUSD&interval=5&from='
current_unixtime = int(time.time())
last_minute = math.floor(current_unixtime / 60)
last_minute_unixtime = str(last_minute * 60 - 300)
query_url = ''.join([base_url, last_minute_unixtime])
response = requests.get(query_url)
if response.status_code == 200: # check if the request was successful
bybit_ohlc = response.json()
candle_stick_data = {
'exchange': 'bybit',
'timestamp': bybit_ohlc['result'][0]['open_time'],
'open': bybit_ohlc['result'][0]['open'],
'high': bybit_ohlc['result'][0]['high'],
'low': bybit_ohlc['result'][0]['low'],
'close': bybit_ohlc['result'][0]['close'],
'volume_quote': bybit_ohlc['result'][0]['volume'],
'volume_base': bybit_ohlc['result'][0]['turnover'],
'trades': 0
}
bybit_json = json.dumps(candle_stick_data, indent=2)
return bybit_json
else:
print(f"Error fetching data from Bybit API: {response.status_code}")
return empty_json
def write_dict_to_database(in_dict, connection): def write_dict_to_database(in_dict, connection):
cursor = connection.cursor() cursor = connection.cursor()
# Use placeholders for the values in the INSERT statement # 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 (?, ?, ?, ?, ?, ?, ?, ?, ?)" insert_query = "insert into ohlc (exchange, timestamp, open, high, low, close, volume_quote, volume_base, trades) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"
values = (in_dict['exchange'], values = (in_dict['exchange'],
in_dict['timestamp'], in_dict['timestamp'],
@ -191,30 +226,61 @@ def get_the_data():
write_dict_to_database(json.loads(fetch_bitfinex()), 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_bitstamp()), db)
write_dict_to_database(json.loads(fetch_gemini()), db) write_dict_to_database(json.loads(fetch_gemini()), db)
write_dict_to_database(json.loads(fetch_bybit()), db)
db.close() db.close()
print("fetches done at", time.time(), "sleeping now for 290") print("fetches done at", time.time(), "sleeping now for 290")
time.sleep(290) time.sleep(290)
def check_auth(text, signature):
print(text)
print(signature)
sig_bytes = bytes.fromhex(signature)
access_granted = 0
## We will iterate over all user keys to determ who is we are talking to and should they have access
for key, value in user_publickeys.items():
## What f*ck even is this?
vk = ecdsa.VerifyingKey.from_string(sig_bytes.fromhex(value), curve=ecdsa.SECP256k1)
if vk.verify(sig_bytes, text):
print('user is', key)
access_granted = 1
if access_granted != 0:
return True
else:
return False
@app.route('/') @app.route('/')
def get_data(): def get_data():
# Get the time (t) argument from the url" # Get the time (t) argument from the url"
query_timestamp = request.args.get('t') query_timestamp = request.args.get('t')
# Should we make output pretty for curl users?
query_pretty = request.args.get('pretty') query_pretty = request.args.get('pretty')
# Authentication header, signatured the query with private key of a user
signature = request.headers.get('auth')
get_url = request.url
if not check_auth(get_url, signature):
return 'Error with Authentication', 403
database_lock.acquire() database_lock.acquire()
db = sqlite3.connect(database) db = sqlite3.connect(database)
if query_timestamp: if query_timestamp:
rows = db.execute("SELECT exchange, timestamp, open, high, low, close FROM ohlc WHERE timestamp > ?", (query_timestamp,)).fetchall() rows = db.execute("SELECT exchange, timestamp, open, high, low, close FROM ohlc WHERE timestamp > ? ORDER BY timestamp", (query_timestamp,)).fetchall()
else: else:
rows = db.execute('SELECT exchange, timestamp, open, high, low, close FROM ohlc').fetchall() rows = db.execute('SELECT exchange, timestamp, open, high, low, close FROM ohlc ORDER BY timestamp').fetchall()
query_timestamp = 0 query_timestamp = 0
database_lock.release() database_lock.release()
data = { data = {
"timestamp": time.time(), "timestamp": time.time(),
"rows": rows "rows": rows
} }
# make sha256 checksum and append it to the data object
data_shasum = sha256(json.dumps(data).encode('utf-8')).hexdigest()
updated_data = {"shasum": data_shasum}
updated_data.update(data)
data = updated_data
if query_pretty: if query_pretty:
response = json.dumps(data, indent=2, separators=(';\n', ' :')) response = json.dumps(data, indent=2, separators=(';\n', ' :'))
else: else: