From fc16d4340d69deced2cf9c994c845b226e989b58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=A1s=20S=C3=A1nchez?= Date: Tue, 7 Jan 2025 09:55:16 -0300 Subject: [PATCH] flask and other bits and bobs --- .gitignore | 1 + keys/generate_keys.py | 19 +++++++++ keys/read_key_db.py | 15 +++++++ libraries/earner.py | 45 +++++++++++--------- main.py | 96 +++++++++++++++++++++++++++++++++++-------- 5 files changed, 140 insertions(+), 36 deletions(-) create mode 100644 keys/generate_keys.py create mode 100644 keys/read_key_db.py diff --git a/.gitignore b/.gitignore index f67a755..7c140b7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ __pycache__/ libraries/__pycache__/* libraries/wrappers/__pycache__/* +keys/api_credentials.db *.pyc *.pyo credentials.py diff --git a/keys/generate_keys.py b/keys/generate_keys.py new file mode 100644 index 0000000..622fd59 --- /dev/null +++ b/keys/generate_keys.py @@ -0,0 +1,19 @@ +import uuid +import sqlite3 + + +users = ["user1", "user2", "user3", "user4"] +keys = [] + +for user in users: + keys.append([user,str(uuid.uuid4())]) + + +database_connection = sqlite3.connect("api_credentials.db") +database_cursor = database_connection.cursor() +database_cursor.execute("CREATE TABLE IF NOT EXISTS credentials_table (user TEXT, key TEXT)") + +for pair in keys: + database_cursor.execute('INSERT INTO credentials_table VALUES(?, ?)', pair) +database_connection.commit() +database_connection.close() \ No newline at end of file diff --git a/keys/read_key_db.py b/keys/read_key_db.py new file mode 100644 index 0000000..bf519a1 --- /dev/null +++ b/keys/read_key_db.py @@ -0,0 +1,15 @@ +import sqlite3 + +valid_keys = [] + +database_connection = sqlite3.connect("api_credentials.db") +database_cursor = database_connection.cursor() + +database_cursor.execute("SELECT * FROM credentials_table") +data = database_cursor.fetchall() + + +for line in data: + valid_keys.append(line[1]) + +print(valid_keys) \ No newline at end of file diff --git a/libraries/earner.py b/libraries/earner.py index f32fa57..0e83400 100644 --- a/libraries/earner.py +++ b/libraries/earner.py @@ -19,6 +19,8 @@ class earner: self.trading_balance = 0 self.earning_balance = 0 + self.is_paused = True + self.status_string = "" @@ -26,6 +28,11 @@ class earner: return str(self.connector) + def toggle_pause(self): + self.is_paused = not self.is_paused + return self.is_paused + + def get_last_subscription(self): return {str(self.connector): self.last_subscription_time} @@ -88,30 +95,30 @@ class earner: else: self.earning_balance = None - #Call balance_accounts - target_trading_amount, target_earning_amount = balance_accounts(float(self.trading_balance), - float(self.earning_balance), - self.minimum_amount_in_trading_account, - self.step_size, - self.percentage) - #Check difference - earning_delta = 0 - if self.earning_balance is None: - print(f"{str(self.connector)} - There was an error fetching earning balance") + if not self.is_paused: + target_trading_amount, target_earning_amount = balance_accounts(float(self.trading_balance), + float(self.earning_balance), + self.minimum_amount_in_trading_account, + self.step_size, + self.percentage) + earning_delta = 0 + if self.earning_balance is None: + print(f"{str(self.connector)} - There was an error fetching earning balance") + else: + if float(self.earning_balance)!=0: + earning_delta = target_earning_amount - float(self.earning_balance) + if earning_delta>self.step_size and time.time()-self.last_subscription_time>self.time_between_subscriptions: + self.subscribe(earning_delta) + if earning_delta<-self.step_size and time.time()-self.last_redemption_time>self.time_between_redemptions: + self.redeem(-earning_delta) + print(f"{str(self.connector)} - Difference: {earning_delta}") else: - if float(self.earning_balance)!=0: - earning_delta = target_earning_amount - float(self.earning_balance) - if earning_delta>self.step_size and time.time()-self.last_subscription_time>self.time_between_subscriptions: - self.subscribe(earning_delta) - if earning_delta<-self.step_size and time.time()-self.last_redemption_time>self.time_between_redemptions: - self.redeem(-earning_delta) - print(f"Difference: {earning_delta}") - + paused_string = "| PAUSED - NOT SUBSCRIBING NOR REDEEMING" #Output status to status_string balances_string = f"Trading balance: {float(self.trading_balance):.2f} {self.currency} | Earning balance: {float(self.earning_balance):.2f} {self.currency}" - percentages_string = f"On earn: {float(self.earning_balance)/float(self.trading_balance):.2%}" + percentages_string = f"On earn: {float(self.earning_balance)/float(self.trading_balance):.2%} {paused_string}" self.status_string = f"{self} | {balances_string} | {percentages_string}" \ No newline at end of file diff --git a/main.py b/main.py index f62c246..1c23605 100644 --- a/main.py +++ b/main.py @@ -5,9 +5,36 @@ from libraries.wrappers import earn_okx from libraries.wrappers import earn_gateio from libraries.earner import earner from threading import Thread +from flask import Flask, jsonify, request import time import datetime import json +import sqlite3 + +def load_keys_from_db(file_name: str) -> list: + ''' + Load valid API keys + + Parameters + ---------- + file_name : str + Name of the database file + + Returns + ------- + valid_keys : list + List of valid API keys + ''' + + database_connection = sqlite3.connect(file_name) + database_cursor = database_connection.cursor() + database_cursor.execute("SELECT * FROM credentials_table") + data = database_cursor.fetchall() + database_connection.close() + + valid_keys = [line[1] for line in data] + + return valid_keys def seconds_to_time(total_seconds: float) -> str: @@ -31,23 +58,7 @@ def seconds_to_time(total_seconds: float) -> str: return f"{time_delta.days}:{hours:02d}:{minutes:02d}:{seconds:02d}" -if __name__=="__main__": - - version = "2025.01.06" - start_time = time.time() - - with open("config.json") as f: - config = json.load(f) - - connectors = {"binance": earn_binance.binance_earn(), - "gateio": earn_gateio.gateio_earn(), - "kucoin": earn_kucoin.kucoin_earn(), - "okx": earn_okx.okx_earn()} - earners = [] - - for item in config["exchanges"]: - earners.append(earner(connectors[item], config["exchanges"][item])) - +def main(): while True: threads = [] @@ -93,6 +104,57 @@ if __name__=="__main__": #Wait for next lap time.sleep(config["lap_time"]) + + + +######################### +######### API ########### +######################### + +earn_api = Flask(__name__) + +@earn_api.route("/toggle_pause", methods=['POST']) +def return_global_status(): + ''' + GET request + + Parameters: + broker: str + ''' + + if "X-API-KEY" in request.headers and request.headers.get("X-API-KEY") in valid_keys: + if request.json is None: + return jsonify({'Error': 'request.json is None'}) + broker = request.json["broker"] + for item in earners: + if str(item.connector)==broker: + item.toggle_pause() + return jsonify({'Status': item.is_paused}) + return jsonify({'Error': 'broker not found'}) + return jsonify({'Error': 'API key invalid'}), 401 + + +if __name__=="__main__": + + version = "2025.01.07" + start_time = time.time() + + with open("config.json") as f: + config = json.load(f) + + connectors = {"binance": earn_binance.binance_earn(), + "gateio": earn_gateio.gateio_earn(), + "kucoin": earn_kucoin.kucoin_earn(), + "okx": earn_okx.okx_earn()} + earners = [] + + for item in config["exchanges"]: + earners.append(earner(connectors[item], config["exchanges"][item])) + + #Load valid API keys + valid_keys = load_keys_from_db("keys/api_credentials.db") + + main()