Compare commits

..

No commits in common. "main" and "2025.05.05" have entirely different histories.

11 changed files with 2172 additions and 3150 deletions

1
.gitignore vendored
View File

@ -17,7 +17,6 @@ logs/gateio.log
logs/kucoin.log logs/kucoin.log
upload_testnet.sh upload_testnet.sh
upload_mainnet.sh upload_mainnet.sh
upload_local_testnet.sh
utils/data/binance.db utils/data/binance.db
utils/data/okx.db utils/data/okx.db
utils/data/gateio.db utils/data/gateio.db

View File

@ -1,188 +1,5 @@
2025.12.01:
. Modified log output of new_market_order.
. Modified Kucoin's case in min_amount_of_base.
2025.11.11:
. deals_cache and log_list cache are now 20 items long.
. Less log spam.
2025.11.08:
. broker.set_default_order_size() now saves the config file to disk after changing the value.
. Variable renaming and other small stuff.
2025.10.24:
. Toggling liquidate_after_switch now writes the config file to disk so the setting persists between trades.
. Manually switching to long now sets double_check_price to false.
. Added a few comments to switch_to_long.
2025.10.12:
. do_cleanup relocated after generating the safety orders' prices.
2025.10.11:
. Minor simplification in do_cleanup.
. Removed a couple of (no longer needed?) pauses.
2025.10.10:
. New endpoint: /refresh_log_cache.
. Fixed an error in /add_so endpoint that incremented the config setting but not the status setting.
2025.10.09:
. Cleanup is done as soon as the trader starts, rather than after sending the take profit and safety orders.
2025.10.07:
. In short traders, if there are too few safety orders (less than 67% of the max amount), safety_order_deviance is increased from 2% to 3%.
2025.10.04:
. Fixed error while logging orders in new_simulated_market_order.
. renew_tp_and_so_routine now send the take profit order first, and then the safety orders.
2025.10.03:
. New broker config option: log_orders. If set to True, the orders will be logged in orders.log under logs directory.
. New API endpoint: /toggle_log_orders.
2025.10.01:
. Fixed base fees not being taken into account.
2025.09.27:
. Added notes in every entry of deal_order_history.
. Minor refactor in renew_tp_and_so_routine.
. Added another cooldown before sending a take profit order (To give the exchange a bit more time to reflect correctly the amount of base present in the account)
. Updated cleanup routine to leave some change in the account.
2025.09.25:
. Added a pause after getting filled orders in check_status.
. Added an extra logging line in take_profit_routine.
2025.09.24:
. Added a new config option: wait_after_initial_market_order. If specifies in seconds the amount of wait time after sending the initial market order.
It should help the exchanges to report correctly the recently filled market order.
. Removed the "PAUSED" notice in the screen output that was unused.
2025.09.21:
. Fixed a bug that caused short traders to have an incorrect order size.
2025.09.20:
. Fixed bug that caused short traders to initialize using the same workflow as a long one.
2025.09.19:
. Added pageSize parameter to the open order requests when querying Kucoin.
2025.09.18:
. do_cleanup now uses get_min_quote_size.
. Added an extra price check to switch_to_long.
. Removed old check_old_long_price method.
2025.09.14:
. Refactored full order list fetching.
. Minor refactor of restart_pair_no_json.
. Pausing the trader is now done via set_pause() method.
. Reverted modification of wait time after initial market order.
. wait_time now present in broker config file.
. Minor refactorings.
2025.09.13:
. Increased wait time after initial market order.
2025.09.12:
. No retries when sending a cleanup order.
. Removed redundant try...except blocks in switch_to_long.
2025.09.11:
. Fixed bug in start_trader that called amount_to_precision with very low amounts and spammed logs.
2025.09.10:
. Deal order history now stores only the id of each order instead of the full order object.
2025.09.08:
. Re-enabled long to short autoswitch.
2025.09.07:
. Increased wait time after sending market orders.
2025.09.05:
. Now the trader supports multiple safety orders at the same time.
. Removed forcing orders when importing a trader. Maybe it will be reinstated at a later date.
. Removed endpoint /reload_safety_orders.
. New endpoints: /mod_concurrent_safety orders, /mod_boosted_concurrent_safety_orders and /force_trader_close.
. Modified cleanup routine.
. Default wait_time back to 0.5 seconds.
. General optimizations.
2025.08.19:
. Improved log trimming.
2025.08.18:
. Database handling optimization.
2025.08.17:
. Minor refactorings.
2025.08.16:
. Improved threading.
2025.08.15:
. "deal order history" is now disabled by default.
. CPU optimizations in status string generation.
2025.08.14:
. Refactored gib_so_size.
. Refactored seconds_to_time.
. Refactored linear_space.
. Refactored dca_cost_calculator.
. Refactored return_optimal_order_size.
. Minor refactor in generate_status_strings.
. Optimized imports.
. Deal_order_history now only stores the important parts of the orders to save some RAM.
. Removed deprecated "profit_to_file" method.
2025.08.12:
. Default "check_slippage" value now True.
. Removed capitalization from exchange name when sending trader quit notification.
. Exception handling when sending Telegram messages.
2025.08.10:
. Added exchange name to the trader quit notification.
. New endpoint: mod_default_order_size. It modifies the default order size of a broker.
. Added "generated_at" field to any new generated trader config file.
2025.07.21:
. Corrected an error in switch_to_long.
2025.07.18:
. Changed Waitress' logging level to ERROR.
2025.07.11:
. Default "check_slippage" value now False.
. The default order size is now enforced per exchange.
. Reinstated config reloading when a deal is closed.
. New endpoint: mod_order_size.
2025.06.04:
. Added "base_add_calculation" endpoint: Calculates how many safety orders can be added with the amount of base currency available on the exchange.
2025.05.31:
. Added "liquidate after switch": Once the short trader is ready to switch to long, it liquidates the base currency and shuts down the trader.
2025.05.27:
. Commented out parameter validation in config and status handlers.
2025.05.26:
. Added closed order request wrappers in exchange_wrapper.
. In check_status: autoswitch prior to order check.
2025.05.18:
. In start_trader, missing base is calculated using amount_to_precision.
2025.05.16:
. Added exception handling when removing a trader.
. Minor variable renaming.
2025.05.12:
. Improved config file handling when switching to long or short.
. If the config file does not exist, it creates it.
2025.05.05: 2025.05.05:
. Forced Telegram message when quit flag is raised. . Forced Telegram message when a quit flag is raised.
2025.05.04: 2025.05.04:
. Simplified unwrapped_add_pair. . Simplified unwrapped_add_pair.

View File

@ -1,5 +1,4 @@
from time import time import json
from json import dumps, load
class ConfigHandler: class ConfigHandler:
''' '''
@ -11,11 +10,9 @@ class ConfigHandler:
self.default_config_dictionary = { self.default_config_dictionary = {
"pair": pair, "pair": pair,
"is_short": False, "is_short": False,
"order_size": self.broker.get_default_order_size(), "order_size": 12,
"no_of_safety_orders": 30, "no_of_safety_orders": 30,
"max_short_safety_orders": 45, "max_short_safety_orders": 45,
"concurrent_safety_orders": 3,
"boosted_concurrent_safety_orders": 5,
"safety_order_deviance": 2, "safety_order_deviance": 2,
"safety_order_scale": 0.0105, "safety_order_scale": 0.0105,
"dynamic_so_deviance": True, "dynamic_so_deviance": True,
@ -23,7 +20,6 @@ class ConfigHandler:
"dsd_range": 1, "dsd_range": 1,
"cleanup": True, "cleanup": True,
"autoswitch": False, "autoswitch": False,
"liquidate_after_switch": False,
"attempt_restart": True, "attempt_restart": True,
"tp_mode": 3, "tp_mode": 3,
"tp_level": 1.025, "tp_level": 1.025,
@ -37,26 +33,17 @@ class ConfigHandler:
"force_restart_if_retries_exhausted": False, "force_restart_if_retries_exhausted": False,
"check_old_long_price": False #switch_to_short should flip this to True unless stated "check_old_long_price": False #switch_to_short should flip this to True unless stated
} }
# if self.broker.get_exchange_name()=="kucoin":
# self.default_config_dictionary["concurrent_safety_orders"]=1
# self.default_config_dictionary["boosted_concurrent_safety_orders"]=1
self.config_file_path = f"configs/{pair.split('/')[0]}{pair.split('/')[1]}.json" self.config_file_path = f"configs/{pair.split('/')[0]}{pair.split('/')[1]}.json"
self.config_dictionary = self.default_config_dictionary.copy() self.config_dictionary = self.default_config_dictionary.copy()
#Loads from disk the config file (if it exists) #Loads from disk the config file (if it exists)
if self.load_from_file()==1: self.load_from_file()
#If the config file does not exist, write a new one with the default values and sign it with timestamp.
self.config_dictionary["generated_at"] = int(time())
self.save_to_file()
if config_dict is not None: if config_dict is not None:
self.config_dictionary.update(config_dict) self.config_dictionary = {**self.config_dictionary, **config_dict}
self.save_to_file() self.save_to_file()
def reset_to_default(self):
self.config_dictionary = self.default_config_dictionary.copy()
return 0
def get_pair(self): def get_pair(self):
return self.config_dictionary["pair"] return self.config_dictionary["pair"]
@ -73,12 +60,6 @@ class ConfigHandler:
def get_max_short_safety_orders(self): def get_max_short_safety_orders(self):
return self.config_dictionary["max_short_safety_orders"] return self.config_dictionary["max_short_safety_orders"]
def get_concurrent_safety_orders(self):
return self.config_dictionary["concurrent_safety_orders"]
def get_boosted_concurrent_safety_orders(self):
return self.config_dictionary["boosted_concurrent_safety_orders"]
def get_safety_order_deviance(self): def get_safety_order_deviance(self):
return self.config_dictionary["safety_order_deviance"] return self.config_dictionary["safety_order_deviance"]
@ -100,9 +81,6 @@ class ConfigHandler:
def get_autoswitch(self): def get_autoswitch(self):
return self.config_dictionary["autoswitch"] return self.config_dictionary["autoswitch"]
def get_liquidate_after_switch(self):
return self.config_dictionary["liquidate_after_switch"]
def get_attempt_restart(self): def get_attempt_restart(self):
return self.config_dictionary["attempt_restart"] return self.config_dictionary["attempt_restart"]
@ -142,193 +120,105 @@ class ConfigHandler:
def get_config_file_path(self): def get_config_file_path(self):
return self.config_file_path return self.config_file_path
def set_config_file_path(self, new_file_path: str): def set_config_file_path(self, new_file_path):
# if not isinstance(new_file_path, str):
# self.broker.logger.log_this(f"File path provided is not a string",1,self.get_pair())
# return 1
self.config_file_path = new_file_path self.config_file_path = new_file_path
return 0 return 0
def set_pair(self, pair: str): def set_pair(self, pair: str):
# if not isinstance(pair, str):
# self.broker.logger.log_this(f"Pair provided is not a string",1,self.get_pair())
# return 1
self.config_dictionary["pair"] = pair self.config_dictionary["pair"] = pair
return 0 return 0
def set_is_short(self, is_short: bool): def set_is_short(self, is_short: bool):
# if not isinstance(is_short, bool):
# self.broker.logger.log_this(f"Is short provided is not a boolean",1,self.get_pair())
# return 1
self.config_dictionary["is_short"] = is_short self.config_dictionary["is_short"] = is_short
return 0 return 0
def set_order_size(self, order_size): def set_order_size(self, order_size):
# if not isinstance(order_size, (int, float)): #if not isinstance(order_size, (int, float)):
# self.broker.logger.log_this(f"Order size provided is not a number",1,self.get_pair()) # raise ValueError("order_size must be an integer or a float")
# return 1
self.config_dictionary["order_size"] = order_size self.config_dictionary["order_size"] = order_size
return 0 return 0
def set_no_of_safety_orders(self, no_of_safety_orders: int): def set_no_of_safety_orders(self, no_of_safety_orders: int):
# if not isinstance(no_of_safety_orders, int):
# self.broker.logger.log_this(f"No of safety orders provided is not an integer",1,self.get_pair())
# return 1
self.config_dictionary["no_of_safety_orders"] = no_of_safety_orders self.config_dictionary["no_of_safety_orders"] = no_of_safety_orders
return 0 return 0
def set_max_short_safety_orders(self, max_short_safety_orders: int): def set_max_short_safety_orders(self, max_short_safety_orders: int):
# if not isinstance(max_short_safety_orders, int):
# self.broker.logger.log_this(f"Max short safety orders provided is not an integer",1,self.get_pair())
# return 1
self.config_dictionary["max_short_safety_orders"] = max_short_safety_orders self.config_dictionary["max_short_safety_orders"] = max_short_safety_orders
return 0 return 0
def set_concurrent_safety_orders(self, concurrent_safety_orders: int):
# if not isinstance(concurrent_safety_orders, int):
# self.broker.logger.log_this(f"Max concurrent safety orders provided is not an integer",1,self.get_pair())
# return 1
self.config_dictionary["concurrent_safety_orders"] = concurrent_safety_orders
return 0
def set_boosted_concurrent_safety_orders(self, boosted_concurrent_safety_orders: int):
# if not isinstance(concurrent_safety_orders, int):
# self.broker.logger.log_this(f"Max concurrent safety orders provided is not an integer",1,self.get_pair())
# return 1
self.config_dictionary["boosted_concurrent_safety_orders"] = boosted_concurrent_safety_orders
return 0
def set_safety_order_deviance(self, safety_order_deviance: int): def set_safety_order_deviance(self, safety_order_deviance: int):
# if not isinstance(safety_order_deviance, int):
# self.broker.logger.log_this(f"Safety order deviance provided is not an integer",1,self.get_pair())
# return 1
self.config_dictionary["safety_order_deviance"] = safety_order_deviance self.config_dictionary["safety_order_deviance"] = safety_order_deviance
return 0 return 0
def set_safety_order_scale(self, safety_order_scale: float): def set_safety_order_scale(self, safety_order_scale: float):
# if not isinstance(safety_order_scale, float):
# self.broker.logger.log_this(f"Safety order scale provided is not a float",1,self.get_pair())
# return 1
self.config_dictionary["safety_order_scale"] = safety_order_scale self.config_dictionary["safety_order_scale"] = safety_order_scale
return 0 return 0
def set_dynamic_so_deviance(self, dynamic_so_deviance: bool): def set_dynamic_so_deviance(self, dynamic_so_deviance: bool):
# if not isinstance(dynamic_so_deviance, bool):
# self.broker.logger.log_this(f"Dynamic safety order deviance provided is not a boolean",1,self.get_pair())
# return 1
self.config_dictionary["dynamic_so_deviance"] = dynamic_so_deviance self.config_dictionary["dynamic_so_deviance"] = dynamic_so_deviance
return 0 return 0
def set_bias(self, bias: float): def set_bias(self, bias: float):
# if not isinstance(bias, float):
# self.broker.logger.log_this(f"Bias provided is not a float",1,self.get_pair())
# return 1
self.config_dictionary["bias"] = bias self.config_dictionary["bias"] = bias
return 0 return 0
def set_dsd_range(self, dsd_range): def set_dsd_range(self, dsd_range):
# if not isinstance(dsd_range, (int, float)): #if not isinstance(dsd_range, (int, float)):
# self.broker.logger.log_this(f"dsd_range must be an int or a float",1,self.get_pair()) # raise ValueError("dsd_range must be an integer or a float")
# return 1
self.config_dictionary["dsd_range"] = dsd_range self.config_dictionary["dsd_range"] = dsd_range
return 0 return 0
def set_cleanup(self, cleanup: bool): def set_cleanup(self, cleanup: bool):
# if not isinstance(cleanup, bool):
# self.broker.logger.log_this(f"cleanup must be a boolean",1,self.get_pair())
# return 1
self.config_dictionary["cleanup"] = cleanup self.config_dictionary["cleanup"] = cleanup
return 0 return 0
def set_autoswitch(self, autoswitch: bool): def set_autoswitch(self, autoswitch: bool):
# if not isinstance(autoswitch, bool):
# self.broker.logger.log_this(f"autoswitch must be a boolean",1,self.get_pair())
# return 1
self.config_dictionary["autoswitch"] = autoswitch self.config_dictionary["autoswitch"] = autoswitch
return 0 return 0
def set_liquidate_after_switch(self, liquidate_after_switch: bool):
# if not isinstance(liquidate_after_switch, bool):
# self.broker.logger.log_this(f"liquidate_after_switch must be a boolean",1,self.get_pair())
# return 1
self.config_dictionary["liquidate_after_switch"] = liquidate_after_switch
self.save_to_file()
return 0
def set_tp_mode(self, tp_mode: int): def set_tp_mode(self, tp_mode: int):
# if not isinstance(tp_mode, int):
# self.broker.logger.log_this(f"tp_mode must be an integer",1,self.get_pair())
# return 1
self.config_dictionary["tp_mode"] = tp_mode self.config_dictionary["tp_mode"] = tp_mode
return 0 return 0
def set_tp_level(self, tp_level: float): def set_tp_level(self, tp_level: float):
# if not isinstance(tp_level, float):
# self.broker.logger.log_this(f"tp_level must be a float",1,self.get_pair())
# return 1
self.config_dictionary["tp_level"] = tp_level self.config_dictionary["tp_level"] = tp_level
return 0 return 0
def set_tp_table(self, tp_table: list): def set_tp_table(self, tp_table: list):
# if not isinstance(tp_table, list):
# self.broker.logger.log_this(f"tp_table must be a list",1,self.get_pair())
# return 1
self.config_dictionary["tp_table"] = tp_table self.config_dictionary["tp_table"] = tp_table
return 0 return 0
def set_check_slippage(self, check_slippage: bool): def set_check_slippage(self, check_slippage: bool):
# if not isinstance(check_slippage, bool):
# self.broker.logger.log_this(f"check_slippage must be a boolean",1,self.get_pair())
# return 1
self.config_dictionary["check_slippage"] = check_slippage self.config_dictionary["check_slippage"] = check_slippage
return 0 return 0
def set_programmed_stop(self, programmed_stop: bool): def set_programmed_stop(self, programmed_stop: bool):
# if not isinstance(programmed_stop, bool):
# self.broker.logger.log_this(f"programmed_stop must be a boolean",1,self.get_pair())
# return 1
self.config_dictionary["programmed_stop"] = programmed_stop self.config_dictionary["programmed_stop"] = programmed_stop
return 0 return 0
def set_programmed_stop_time(self, programmed_stop_time): def set_programmed_stop_time(self, programmed_stop_time):
# if not isinstance(programmed_stop_time, (int,float)): #if not isinstance(programmed_stop_time, (int, float)):
# self.broker.logger.log_this(f"programmed_stop_time must be an int or a float",1,self.get_pair()) # raise ValueError("programmed_stop_time be an integer or a float")
# return 1
self.config_dictionary["programmed_stop_time"] = programmed_stop_time self.config_dictionary["programmed_stop_time"] = programmed_stop_time
return 0 return 0
def set_boosted_deals_range(self, boosted_deals_range: int): def set_boosted_deals_range(self, boosted_deals_range: int):
# if not isinstance(boosted_deals_range, int):
# self.broker.logger.log_this(f"boosted_deals_range must be an int",1,self.get_pair())
# return 1
self.config_dictionary["boosted_deals_range"] = boosted_deals_range self.config_dictionary["boosted_deals_range"] = boosted_deals_range
return 0 return 0
def set_boosted_time_range(self, boosted_time_range: int): def set_boosted_time_range(self, boosted_time_range: int):
# if not isinstance(boosted_time_range, int):
# self.broker.logger.log_this(f"boosted_time_range must be an int",1,self.get_pair())
# return 1
self.config_dictionary["boosted_time_range"] = boosted_time_range self.config_dictionary["boosted_time_range"] = boosted_time_range
return 0 return 0
def set_boosted_amount(self, boosted_amount: float): def set_boosted_amount(self, boosted_amount: float):
# if not isinstance(boosted_amount, float):
# self.broker.logger.log_this(f"boosted_amount must be a float",1,self.get_pair())
# return 1
self.config_dictionary["boosted_amount"] = boosted_amount self.config_dictionary["boosted_amount"] = boosted_amount
return 0 return 0
def set_force_restart_if_retries_exhausted(self, force_restart_if_retries_exhausted: bool): def set_force_restart_if_retries_exhausted(self, force_restart_if_retries_exhausted: bool):
# if not isinstance(force_restart_if_retries_exhausted, bool):
# self.broker.logger.log_this(f"force_restart_if_retries_exhausted must be a bool",1,self.get_pair())
# return 1
self.config_dictionary["force_restart_if_retries_exhausted"] = force_restart_if_retries_exhausted self.config_dictionary["force_restart_if_retries_exhausted"] = force_restart_if_retries_exhausted
return 0 return 0
def set_check_old_long_price(self, check_old_long_price: bool): def set_check_old_long_price(self, check_old_long_price: bool):
# if not isinstance(check_old_long_price, bool):
# self.broker.logger.log_this(f"check_old_long_price must be a bool",1,self.get_pair())
# return 1
self.config_dictionary["check_old_long_price"] = check_old_long_price self.config_dictionary["check_old_long_price"] = check_old_long_price
return 0 return 0
@ -336,12 +226,9 @@ class ConfigHandler:
def save_to_file(self, file_path = None): def save_to_file(self, file_path = None):
if file_path is None: if file_path is None:
file_path = self.config_file_path file_path = self.config_file_path
# if not isinstance(file_path, str):
# self.broker.logger.log_this(f"file_path must be a string",1,self.get_pair())
# return 1
try: try:
with open(file_path, "w") as f: with open(file_path, "w") as f:
f.write(dumps(self.config_dictionary, indent=4)) f.write(json.dumps(self.config_dictionary, indent=4))
return 0 return 0
except Exception as e: except Exception as e:
self.broker.logger.log_this(f"Error saving config to file: {file_path}: {e}",1,self.get_pair()) self.broker.logger.log_this(f"Error saving config to file: {file_path}: {e}",1,self.get_pair())
@ -350,12 +237,9 @@ class ConfigHandler:
def load_from_file(self, file_path = None): def load_from_file(self, file_path = None):
if file_path is None: if file_path is None:
file_path = self.config_file_path file_path = self.config_file_path
# if not isinstance(file_path, str):
# self.broker.logger.log_this(f"file_path must be a string",1,self.get_pair())
# return 1
try: try:
with open(file_path, "r") as f: with open(file_path, "r") as f:
self.set_config({**self.default_config_dictionary, **load(f)}) self.set_config({**self.default_config_dictionary, **json.load(f)})
return 0 return 0
except Exception as e: except Exception as e:
self.broker.logger.log_this(f"Config file does not exist or is not readable: {e}",1,self.get_pair()) self.broker.logger.log_this(f"Config file does not exist or is not readable: {e}",1,self.get_pair())
@ -368,8 +252,5 @@ class ConfigHandler:
''' '''
Validates every key in the config dictionary and sets the config dictionary Validates every key in the config dictionary and sets the config dictionary
''' '''
# if not isinstance(config_dictionary, dict):
# self.broker.logger.log_this(f"config_dictionary must be a dictionary",1,self.get_pair())
# return 1
self.config_dictionary = config_dictionary self.config_dictionary = config_dictionary
return 0 return 0

View File

@ -1,10 +1,8 @@
import collections import json
import time import time
import requests
import credentials import credentials
import sqlite3 import sqlite3
from contextlib import contextmanager
from requests import get as requests_get
from json import load, dumps
from copy import deepcopy from copy import deepcopy
@ -14,29 +12,24 @@ class Broker:
self.broker_config = broker_config self.broker_config = broker_config
self.exchange = exchange self.exchange = exchange
self.last_price = 0 self.last_price = 0
self.wait_time = 1 #Default wait time for API breathing room
self.cooldown_multiplier = 2 #Default cooldown multiplier value
if "cooldown_multiplier" in self.broker_config:
self.cooldown_multiplier = self.broker_config["cooldown_multiplier"]
self.wait_before_new_safety_order = 1
if "wait_before_new_safety_order" in self.broker_config:
self.wait_before_new_safety_order = self.broker_config["wait_before_new_safety_order"]
self.empty_order = {"id": "", "status": "", "filled": 0, "remaining": 0, "price": 0, "cost": 0, "fees": [], "symbol": ""} self.empty_order = {"id": "", "status": "", "filled": 0, "remaining": 0, "price": 0, "cost": 0, "fees": [], "symbol": ""}
self.retries = self.broker_config["retries"] if "retries" in self.broker_config else 5
#Default values self.slippage_default_threshold = self.broker_config["slippage_default_threshold"] if "slippage_default_threshold" in self.broker_config else .03
self.wait_time = self.broker_config.get("wait_time",.5)
self.cooldown_multiplier = self.broker_config.get("cooldown_multiplier",2)
self.wait_after_initial_market_order = self.broker_config.get("wait_after_initial_market_order",1)
self.wait_before_new_safety_order = self.broker_config.get("wait_before_new_safety_order",1)
self.retries = self.broker_config.get("retries",5)
self.slippage_default_threshold = self.broker_config.get("slippage_default_threshold",.03)
self.follow_order_history = self.broker_config.get("follow_order_history",False)
self.write_order_history = self.broker_config.get("write_order_history", False)
self.logger = Logger(self.broker_config) self.logger = Logger(self.broker_config)
self.log_orders = self.broker_config.get("log_orders",False) self.write_order_history = True #This should be a toggle in config_file
#Initialize database #Initialize database
self.profits_database_filename = "profits/profits_database.db" self.profits_database_filename = "profits/profits_database.db"
self.database_connection = sqlite3.connect(self.profits_database_filename)
self._db = sqlite3.connect(self.profits_database_filename, self.database_cursor = self.database_connection.cursor()
detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES, self.database_cursor.execute('''
check_same_thread=False)
self._db.row_factory = sqlite3.Row
with self._db:
self._db.execute('''
CREATE TABLE IF NOT EXISTS profits_table ( CREATE TABLE IF NOT EXISTS profits_table (
timestamp REAL PRIMARY KEY, timestamp REAL PRIMARY KEY,
pair TEXT, pair TEXT,
@ -46,35 +39,26 @@ class Broker:
order_history TEXT order_history TEXT
) )
''') ''')
self.database_connection.commit()
self.database_connection.close()
#Load markets #Load markets
self.markets = self.exchange.load_markets() self.markets = self.exchange.load_markets()
#Populates deals cache #Populates deals cache
self.deals_cache_length = 20 self.deals_cache_length = 10
self.deals_list = self.preload_deals(amount_to_preload=self.deals_cache_length) self.deals_list = self.preload_deals(amount_to_preload=self.deals_cache_length)
@contextmanager
def _cur(self):
'''
Database cursor
'''
cur = self._db.cursor()
try:
yield cur
finally:
cur.close()
def preload_deals(self,amount_to_preload=10): def preload_deals(self,amount_to_preload=10):
''' '''
Reads the last n deals from the database and returns them in a list Reads the last n deals from the database and returns them in a list
''' '''
query = "SELECT * FROM profits_table WHERE exchange_name = ? ORDER BY timestamp DESC LIMIT ?" connection = sqlite3.connect(self.profits_database_filename)
with self._cur() as cur: cursor = connection.cursor()
cur.execute(query, (self.get_exchange_name(), amount_to_preload)) cursor.execute(f"SELECT * FROM profits_table WHERE exchange_name = ? ORDER BY timestamp DESC LIMIT ?", (self.get_exchange_name(), amount_to_preload))
result = cur.fetchall() result = cursor.fetchall()
connection.close()
return [(row[0],row[1],row[2],row[3],row[4],"") for row in result] return [(row[0],row[1],row[2],row[3],row[4],"") for row in result]
@ -82,16 +66,6 @@ class Broker:
def get_deals_cache(self): def get_deals_cache(self):
return self.deals_list return self.deals_list
def get_log_orders(self):
return self.log_orders
def set_log_orders(self,log_orders:bool):
self.log_orders = log_orders
return 0
def get_symbol(self,pair): def get_symbol(self,pair):
if "/" in pair: if "/" in pair:
return pair return pair
@ -146,13 +120,21 @@ class Broker:
Returns the timestamps of the last trades from the database for the boosting algorithm Returns the timestamps of the last trades from the database for the boosting algorithm
''' '''
limit = time.time()-timespan retries = self.retries
query = "SELECT * FROM profits_table WHERE timestamp >= ? ORDER BY timestamp" while retries>0:
try:
with self._cur() as cur: database_connection = sqlite3.connect(self.profits_database_filename)
cur.execute(query,(limit,)) database_cursor = database_connection.cursor()
rows = cur.fetchall() database_cursor.execute(f"SELECT * FROM profits_table WHERE timestamp >= {time.time()-timespan} ORDER BY timestamp")
rows = database_cursor.fetchall()
return [item[0] for item in rows if item[1]==pair] return [item[0] for item in rows if item[1]==pair]
except Exception as e:
self.logger.log_this(f"Exception in preload_timestamps: {e}")
if no_retries:
break
retries-=1
time.sleep(self.wait_time)
return []
def write_profit_to_cache(self,dataset): def write_profit_to_cache(self,dataset):
@ -169,11 +151,22 @@ class Broker:
''' '''
dataset format: (timestamp,pair,amount,exchange_name,order_id,order_history) dataset format: (timestamp,pair,amount,exchange_name,order_id,order_history)
''' '''
retries = self.retries
query = "INSERT INTO profits_table VALUES(?, ?, ?, ?, ?, ?)" while retries>0:
with self._db: try:
self._db.execute(query, dataset) database_connection = sqlite3.connect(self.profits_database_filename)
database_cursor = database_connection.cursor()
database_cursor.execute('INSERT INTO profits_table VALUES(?, ?, ?, ?, ?, ?)', dataset)
database_connection.commit()
database_connection.close()
except Exception as e:
self.logger.log_this(f"Exception in write_profit_to_db: {e}")
if no_retries:
break
retries-=1
time.sleep(self.wait_time)
return 0 return 0
return 1
def check_for_duplicate_profit_in_db(self,order,no_retries=False): def check_for_duplicate_profit_in_db(self,order,no_retries=False):
@ -182,21 +175,29 @@ class Broker:
Compares the id of the last profit order with the one in the database. Compares the id of the last profit order with the one in the database.
''' '''
query = f"SELECT * FROM profits_table WHERE pair = ? ORDER BY timestamp DESC LIMIT 1;" retries = self.retries
with self._cur() as cur: while retries>0:
cur.execute(query, (order["symbol"],)) try:
result = cur.fetchone() database_connection = sqlite3.connect(self.profits_database_filename)
if result is None: database_cursor = database_connection.cursor()
database_cursor.execute(f"SELECT * FROM profits_table WHERE pair = '{order['symbol']}' ORDER BY timestamp DESC LIMIT 1;")
rows = database_cursor.fetchall()
database_connection.close()
if rows==[]:
return False
return order["id"]==rows[0][4]
except Exception as e:
self.logger.log_this(f"Exception in check_for_duplicate_profit_in_db: {e}",1)
if no_retries:
break
retries-=1
time.sleep(self.wait_time)
return False return False
return order["id"]==result[4]
def get_write_order_history(self): def get_write_order_history(self):
return self.write_order_history return self.write_order_history
def get_follow_order_history(self):
return self.follow_order_history
def get_cooldown_multiplier(self): def get_cooldown_multiplier(self):
return self.cooldown_multiplier return self.cooldown_multiplier
@ -204,13 +205,6 @@ class Broker:
self.cooldown_multiplier = value self.cooldown_multiplier = value
return 0 return 0
def get_wait_after_initial_market_order(self):
return self.wait_after_initial_market_order
def set_wait_after_initial_market_order(self, value:float):
self.wait_after_initial_market_order = value
return 0
def get_wait_before_new_safety_order(self): def get_wait_before_new_safety_order(self):
return self.wait_before_new_safety_order return self.wait_before_new_safety_order
@ -224,7 +218,6 @@ class Broker:
def set_default_order_size(self,size): def set_default_order_size(self,size):
try: try:
self.broker_config["default_order_size"] = float(size) self.broker_config["default_order_size"] = float(size)
self.rewrite_config_file()
except Exception as e: except Exception as e:
self.logger.log_this(f"Exception in set_default_order_size: {e}",1) self.logger.log_this(f"Exception in set_default_order_size: {e}",1)
return 1 return 1
@ -297,7 +290,7 @@ class Broker:
def reload_config_file(self): def reload_config_file(self):
try: try:
with open(self.config_filename) as f: with open(self.config_filename) as f:
self.broker_config = load(f) self.broker_config = json.load(f)
except Exception as e: except Exception as e:
self.logger.log_this(f"Exception while reading the config file: {e}",1) self.logger.log_this(f"Exception while reading the config file: {e}",1)
@ -347,9 +340,9 @@ class Broker:
try: try:
if backup: if backup:
with open(f"{self.exchange}.bak","w") as c: with open(f"{self.exchange}.bak","w") as c:
c.write(dumps(self.broker_config, indent=4)) c.write(json.dumps(self.broker_config, indent=4))
with open(f"{self.config_filename}","w") as f: with open(f"{self.config_filename}","w") as f:
f.write(dumps(self.broker_config, indent=4)) f.write(json.dumps(self.broker_config, indent=4))
return 0 return 0
except Exception as e: except Exception as e:
self.logger.log_this(f"Problems writing the config file. Exception: {e}",1) self.logger.log_this(f"Problems writing the config file. Exception: {e}",1)
@ -397,13 +390,10 @@ class Broker:
if self.get_exchange_name()=="binance": if self.get_exchange_name()=="binance":
a = self.exchange.fetch_last_prices(pair_list) a = self.exchange.fetch_last_prices(pair_list)
return {x: a[x]["price"] for x in a.keys()} return {x: a[x]["price"] for x in a.keys()}
elif self.get_exchange_name()=="kucoin":
a = self.exchange.fetch_tickers(pair_list)
if pair_list is None:
return {x: a[x]["close"] for x in a.keys()}
return {x: a[x]["close"] for x in a.keys() if x in pair_list}
else: else:
#a = self.exchange.fetch_tickers(pair_list)
a = self.exchange.fetch_tickers() a = self.exchange.fetch_tickers()
#return {x.upper(): a[x]["close"] for x in a.keys() if x.upper() in pair_list}
if pair_list is None: if pair_list is None:
return {x: a[x]["close"] for x in a.keys()} return {x: a[x]["close"] for x in a.keys()}
return {x: a[x]["close"] for x in a.keys() if x in pair_list} return {x: a[x]["close"] for x in a.keys() if x in pair_list}
@ -424,10 +414,13 @@ class Broker:
:param no_retries: if True, will not retry if exception occurs :param no_retries: if True, will not retry if exception occurs
:return: closing price of trading pair :return: closing price of trading pair
''' '''
retries = self.retries retries = self.retries
while retries>0: while retries>0:
try: try:
self.last_price = self.exchange.fetch_ticker(symbol)["close"] pair = symbol
a = self.exchange.fetch_ticker(pair)
self.last_price = a["close"]
return self.last_price return self.last_price
except Exception as e: except Exception as e:
self.logger.log_this(f"Exception in get_ticker_price: {e}",1) self.logger.log_this(f"Exception in get_ticker_price: {e}",1)
@ -478,7 +471,7 @@ class Broker:
try: try:
return orderbook["bids"][0][0] return orderbook["bids"][0][0]
except Exception as e: except Exception as e:
self.logger.log_this(f"Exception getting top bid price: {e}",1,symbol) self.logger.log_this(f"Exception getting top mid price: {e}",1,symbol)
return self.get_ticker_price(symbol) return self.get_ticker_price(symbol)
@ -523,56 +516,56 @@ class Broker:
return [] return []
def fetch_open_orders(self,pairs=None) -> list: def fetch_full_orders(self,pairs=None) -> list:
''' '''
Returns a list of all open orders on the exchange Returns a list of all orders on the exchange
:param pairs: list of pairs to get opened orders :param pairs: list of pairs to get orders for
:return: list of all open orders :return: list of orders
''' '''
if pairs is None: if pairs is None:
pairs = [] pairs = []
try: try:
orders = []
if self.get_exchange_name()=="binance": if self.get_exchange_name()=="binance":
if self.broker_config.get("unified_order_query"): orders = self.get_opened_orders_binance(pairs)
return self.exchange.fetch_open_orders()
result = []
for pair in pairs:
a = self.exchange.fetch_open_orders(pair)
result.extend(iter(a))
return result
elif self.get_exchange_name()=="kucoin":
return self.exchange.fetch_open_orders(params={"pageSize": "500"})
else: else:
return self.exchange.fetch_open_orders() orders = self.get_opened_orders()
return [] if orders is None else orders
except Exception as e:
self.logger.log_this(f"Exception in fetch_full_orders: {e}",2)
return []
def fetch_open_orders(self,pairs=None) -> list:
'''
Returns a list of IDs of all open orders on the exchange
:param pairs: list of pairs to get opened orders
:return: list of IDs of all open orders
'''
if pairs is None:
pairs = []
try:
#id_list = []
if self.get_exchange_name()=="binance":
return self.get_opened_orders_binance(pairs)
return self.get_opened_orders()
#else:
# orders = self.get_opened_orders()
#if orders!=[]:
# id_list.extend(x["id"] for x in orders)
#return id_list
except Exception as e: except Exception as e:
self.logger.log_this(f"Exception in fetch_open_orders: {e}",2) self.logger.log_this(f"Exception in fetch_open_orders: {e}",2)
return [] return []
def fetch_closed_orders(self,pairs=None) -> list: def get_opened_orders(self,no_retries=False): #It should return a list of all opened orders
''' '''
Returns a list of all closed orders on the exchange Returns a list of all the orders on the exchange
:param pairs: list of pairs to get opened orders
:return: list of all open orders
'''
if pairs is None:
pairs = []
try:
if self.get_exchange_name()=="binance":
return self.get_closed_orders_binance(pairs)
return self.get_closed_orders()
except Exception as e:
self.logger.log_this(f"Exception in fetch_closed_orders: {e}",2)
return []
def get_closed_orders(self,pair=None,no_retries=False): #It should return a list of all opened orders
'''
Returns a list of all the open orders on the exchange
:param pairs: list of pairs :param pairs: list of pairs
:return: list of all the open orders on the exchange :return: list of all the open orders on the exchange
@ -581,9 +574,9 @@ class Broker:
retries = self.retries retries = self.retries
while retries>0: while retries>0:
try: try:
return self.exchange.fetch_closed_orders(pair) return self.exchange.fetch_open_orders()
except Exception as e: except Exception as e:
self.logger.log_this(f"Exception in get_closed_orders: {e}",1) self.logger.log_this(f"Exception in get_opened_orders: {e}",1)
if no_retries: if no_retries:
break break
time.sleep(self.wait_time) time.sleep(self.wait_time)
@ -591,24 +584,24 @@ class Broker:
return [] return []
def get_closed_orders_binance(self,pairs): def get_opened_orders_binance(self,pairs):
''' '''
Returns a list of all the closed orders on the exchange Returns a list of all the open orders on the exchange
:param pairs: list of pairs :param pairs: list of pairs
:return: list of all the closed orders on the exchange :return: list of all the open orders on the exchange
''' '''
try: try:
if self.broker_config.get("unified_order_query"): if "unified_order_query" in self.broker_config and self.broker_config["unified_order_query"] is True:
return self.exchange.fetch_closed_orders() return self.exchange.fetch_open_orders()
result = [] result = []
for pair in pairs: for pair in pairs:
a = self.exchange.fetch_closed_orders(pair) a = self.exchange.fetch_open_orders(pair)
result.extend(iter(a)) result.extend(iter(a))
return result return result
except Exception as e: except Exception as e:
self.logger.log_this(f"Exception in get_closed_orders_binance: {e}",1) self.logger.log_this(f"Exception in get_opened_orders_binance: {e}",1)
return [] return []
@ -622,15 +615,16 @@ class Broker:
:return: 0 if order was succesfully canceled, 1 if not :return: 0 if order was succesfully canceled, 1 if not
''' '''
pair = symbol
tries = self.retries//2 tries = self.retries//2
while tries>0: while tries>0:
try: try:
while self.get_order(id,symbol)["status"]=="open": while self.get_order(id,pair)["status"]=="open":
self.exchange.cancel_order(id,symbol) self.exchange.cancel_order(id,symbol=pair)
time.sleep(self.wait_time) time.sleep(self.wait_time)
return 0 return 0
except Exception as e: except Exception as e:
if self.get_order(id,symbol)["status"]=="canceled": if self.get_order(id,pair)["status"]=="canceled":
return 0 return 0
self.logger.log_this(f"Exception in cancel_order: id {id} - exception: {e}",1) self.logger.log_this(f"Exception in cancel_order: id {id} - exception: {e}",1)
if no_retries: if no_retries:
@ -664,7 +658,7 @@ class Broker:
return amount return amount
def new_simulated_market_order(self,symbol,size,side,amount_in_base=False,no_retries=False,log=""): def new_simulated_market_order(self,symbol,size,side,amount_in_base=False,no_retries=False):
''' '''
TODO: Emulating Market Orders With Limit Orders TODO: Emulating Market Orders With Limit Orders
@ -691,29 +685,26 @@ class Broker:
''' '''
retries = self.retries//2 retries = self.retries//2
pair = symbol
while retries>0: while retries>0:
try: try:
if self.get_exchange_name()=="gateio" and side=="buy" and not amount_in_base: if self.get_exchange_name()=="gateio" and side=="buy" and not amount_in_base:
new_order = self.exchange.create_market_buy_order_with_cost(symbol, size) new_order = self.exchange.create_market_buy_order_with_cost(pair, size)
if self.log_orders:
self.logger.log_order(f"New simulated market order: Symbol: {symbol} - Side: {side} - Size: {size} - ID: {new_order['id']} - Origin: {log}")
else: else:
order_book = self.get_order_book(symbol) order_book = self.get_order_book(symbol)
if order_book=={}: if order_book=={}:
self.logger.log_this(f"new_simulated_market_order. Order book returned an empty dictionary",1,symbol) self.logger.log_this(f"new_simulated_market_order. Order book returned an empty dictionary",1,symbol)
return self.empty_order return self.empty_order
if amount_in_base or side!="buy": if amount_in_base or side!="buy":
base_amount = self.amount_to_precision(symbol,size) base_amount = self.amount_to_precision(pair,size)
else: else:
avg_price = self.average_price_depth(order_book,size,"sell") avg_price = self.average_price_depth(order_book,size,"sell")
base_amount = size/avg_price if avg_price is not None else size/self.get_ticker_price(symbol) base_amount = size/avg_price if avg_price is not None else size/self.get_ticker_price(symbol)
price = self.find_minimum_viable_price(order_book,base_amount,side) price = self.find_minimum_viable_price(order_book,base_amount,side)
#Maybe check for slippage here instead of within the trader itself? idk #Maybe check for slippage here instead of within the trader itself? idk
new_order = self.exchange.create_order(symbol,"limit",side,base_amount,price) new_order = self.exchange.create_order(pair,"limit",side,base_amount,price)
if self.log_orders:
self.logger.log_order(f"New simulated market order: Symbol: {symbol} - Side: {side} - Size: {size} - Price: {price} - ID: {new_order['id']} - Origin: {log}")
time.sleep(self.wait_time) time.sleep(self.wait_time)
return self.get_order(new_order["id"],symbol) return self.get_order(new_order["id"],pair)
except Exception as e: except Exception as e:
self.logger.log_this(f"new_simulated_market_order exception: {e}",1,symbol) self.logger.log_this(f"new_simulated_market_order exception: {e}",1,symbol)
if no_retries: if no_retries:
@ -758,7 +749,7 @@ class Broker:
return None return None
def new_market_order(self,symbol,size,side,amount_in_base=False,no_retries=False, log=""): #It should send a new market order to the exchange def new_market_order(self,symbol,size,side,amount_in_base=False,no_retries=False): #It should send a new market order to the exchange
''' '''
Sends a new market order to the exchange. Sends a new market order to the exchange.
@ -772,24 +763,24 @@ class Broker:
if self.broker_config["simulate_market_orders"]: if self.broker_config["simulate_market_orders"]:
return self.new_simulated_market_order(symbol,size,side,amount_in_base=amount_in_base) return self.new_simulated_market_order(symbol,size,side,amount_in_base=amount_in_base)
retries = self.retries retries = self.retries
pair = symbol
while retries>0: while retries>0:
try: try:
if side=="buy": if side=="buy":
to_buy = float(size) to_buy = float(size)
if not amount_in_base: if not amount_in_base:
to_buy = float(size)/self.get_top_ask_price(symbol) to_buy = float(size)/self.get_top_ask_price(pair)
amount = self.amount_to_precision(symbol,to_buy) amount = self.amount_to_precision(pair,to_buy)
else: else:
amount = self.amount_to_precision(symbol,size) #Market sell orders are always nominated in base currency amount = self.amount_to_precision(pair,size) #Market sell orders are always nominated in base currency
order_to_send = self.exchange.create_order(symbol,"market",side,amount) order_to_send = self.exchange.create_order(pair,"market",side,amount)
if self.log_orders:
self.logger.log_order(f"New market order: Symbol: {symbol} - Side: {side} - Size: {size} - ID: {order_to_send['id']} - Origin: {log}")
time.sleep(self.wait_time) time.sleep(self.wait_time)
# Wait a bit more when dealing with Kucoin
return self.get_order(order_to_send["id"],symbol) return self.get_order(order_to_send["id"],pair)
except Exception as e: except Exception as e:
self.logger.log_this(f"Exception in new_market_order: {e} - Side: {side} - Size: {size}",1,symbol) self.logger.log_this(f"Exception in new_market_order: {e}",1,pair)
if no_retries: if no_retries:
break break
time.sleep(self.wait_time) time.sleep(self.wait_time)
@ -837,41 +828,7 @@ class Broker:
return "the lowest price limit for sell orders is" in str(error_object).lower() return "the lowest price limit for sell orders is" in str(error_object).lower()
# def new_limit_orders(self, orders: list) -> list: def new_limit_order(self,symbol,size,side,price,no_retries=False):
# sent_orders = []
# #Send the orders
# tries = self.retries
# while tries>=0:
# try:
# sent_orders = self.exchange.create_orders(orders)
# except Exception as e:
# self.logger.log_this(f"Exception while sending safety orders: {e}",1)
# tries-=1
# time.sleep(self.wait_time)
# if tries==0:
# return []
# #Retrieve the orders from the exchange by id to confirm that they were sent
# #Specially for OKX, since the orders that create_orders return are empty (only id is present)
# returned_orders = []
# for order in sent_orders:
# tries = self.retries
# while tries>=0:
# try:
# returned_orders.append(self.get_order(order["id"],order["symbol"]))
# time.sleep(self.wait_time)
# except Exception as e:
# self.logger.log_this(f"Exception while retrieving safety orders: {e}",1)
# tries-=1
# if tries==0:
# if self.get_exchange_name()=="okex":
# return returned_orders
# returned_orders.append(order) #In the case of the other exchanges, we just assume that the order was sent and append it.
# time.sleep(self.wait_time)
# return returned_orders
def new_limit_order(self,symbol,size,side,price,no_retries=False,log=""):
''' '''
Sends a new limit order. Sends a new limit order.
@ -883,15 +840,20 @@ class Broker:
''' '''
tries = self.retries tries = self.retries
pair = symbol
while tries>=0: while tries>=0:
try: try:
order_to_send = self.exchange.create_order(symbol,"limit",side,self.amount_to_precision(symbol,size),price) order_to_send = self.exchange.create_order(pair,"limit",side,self.amount_to_precision(pair,size),price)
time.sleep(self.wait_time) time.sleep(self.wait_time)
if self.log_orders: return self.get_order(order_to_send["id"],pair)
self.logger.log_order(f"New limit order: Symbol: {symbol} - Side: {side} - Size: {size} - Price: {price} - ID: {order_to_send['id']} - Notes: {log}") #if order_to_send["amount"] is not None: # Because Kucoin etc etc
return self.get_order(order_to_send["id"],symbol) # return self.get_order(order_to_send["id"],pair) #
#self.logger.log_this(f"Error sending order: Null order returned",2,pair) #
#self.cancel_order(order_to_send["id"],symbol,no_retries=True) #
#retries-=1
except Exception as e: except Exception as e:
self.logger.log_this(f"Exception in new_limit_order - Side: {side} - Size: {size} - {self.amount_to_precision(symbol,size)} - Exception: {e}",1,symbol) self.logger.log_this(f"Exception in new_limit_order - Side: {side} - Size: {size} - {self.amount_to_precision(pair,size)} - Exception: {e}",1,symbol)
if self.not_enough_balance_error(e): if self.not_enough_balance_error(e):
if tries<=self.retries//2: #Halves the amount of retries if there is a balance error. if tries<=self.retries//2: #Halves the amount of retries if there is a balance error.
return 1 return 1
@ -922,9 +884,10 @@ class Broker:
if id=="": if id=="":
return self.empty_order return self.empty_order
tries = self.retries tries = self.retries
pair = symbol
while tries>0: while tries>0:
try: try:
return self.exchange.fetch_order(id,symbol) return self.exchange.fetch_order(id,symbol=pair)
except Exception as e: except Exception as e:
self.logger.log_this(f"Exception in get_order: {e}",1,symbol) self.logger.log_this(f"Exception in get_order: {e}",1,symbol)
if no_retries: if no_retries:
@ -942,9 +905,10 @@ class Broker:
:return: The market information. :return: The market information.
''' '''
tries = self.retries tries = self.retries
pair = symbol
while tries>0: while tries>0:
try: try:
return self.exchange.market(symbol) return self.exchange.market(pair)
except Exception as e: except Exception as e:
self.logger.log_this(f"Exception in fetch_market: {e}",1,symbol) self.logger.log_this(f"Exception in fetch_market: {e}",1,symbol)
if no_retries: if no_retries:
@ -962,9 +926,10 @@ class Broker:
:return: The ticker information. :return: The ticker information.
''' '''
tries = self.retries tries = self.retries
pair = symbol
while tries>0: while tries>0:
try: try:
return self.exchange.fetch_ticker(symbol) return self.exchange.fetch_ticker(pair)
except Exception as e: except Exception as e:
self.logger.log_this(f"Exception in get_ticker: {e}") self.logger.log_this(f"Exception in get_ticker: {e}")
if no_retries: if no_retries:
@ -988,9 +953,9 @@ class Broker:
if self.get_exchange_name() in ["okex","bybit"]: if self.get_exchange_name() in ["okex","bybit"]:
return float(market["limits"]["amount"]["min"]) return float(market["limits"]["amount"]["min"])
elif self.get_exchange_name() in ["kucoin"]: elif self.get_exchange_name() in ["kucoin"]:
return max(float(market["limits"]["amount"]["min"]),(float(market["limits"]["cost"]["min"])+.25)/self.get_ticker_price(pair))
elif self.get_exchange_name() in ["gateio"]:
return (float(market["limits"]["cost"]["min"])+.1)/self.get_ticker_price(pair) return (float(market["limits"]["cost"]["min"])+.1)/self.get_ticker_price(pair)
elif self.get_exchange_name() in ["gateio"]:
return (float(market["limits"]["cost"]["min"])+.25)/self.get_ticker_price(pair)
elif self.get_exchange_name()=="binance": elif self.get_exchange_name()=="binance":
for line in market["info"]["filters"]: for line in market["info"]["filters"]:
if line["filterType"] == "NOTIONAL": if line["filterType"] == "NOTIONAL":
@ -1028,8 +993,8 @@ class Broker:
:param pair: pair :param pair: pair
:return: step size :return: step size
'''
'''
market = self.fetch_market(pair) market = self.fetch_market(pair)
if market is None: if market is None:
return None return None
@ -1052,30 +1017,18 @@ class Logger:
self.broker_config = broker_config self.broker_config = broker_config
self.exchange_name = self.broker_config["exchange"] self.exchange_name = self.broker_config["exchange"]
self.tg_credentials = credentials.get_credentials("telegram") self.tg_credentials = credentials.get_credentials("telegram")
self.log_list_max_length = 20 # log cache self.log_list_max_length = 10
self.log_list = collections.deque(maxlen=self.log_list_max_length) self.log_list = self.preload_logs()
self.preload_logs()
def preload_logs(self): def preload_logs(self):
try: try:
with open(f"logs/{self.exchange_name}.log","r") as f: with open(f"logs/{self.exchange_name}.log","r") as f:
for line in f: self.log_list = f.readlines()
self.log_list.append(line.rstrip("\n")) return self.log_list[-self.log_list_max_length:]
return 0
except Exception as e: except Exception as e:
print(e) print(e)
return 1 return []
def refresh_logs(self):
try:
self.log_list.clear()
self.preload_logs()
return 0
except Exception as e:
print(e)
return 1
def set_log_list_max_length(self, amount): def set_log_list_max_length(self, amount):
@ -1084,7 +1037,7 @@ class Logger:
def get_log_list(self): def get_log_list(self):
return list(self.log_list) return self.log_list
def set_telegram_notifications(self, toggle): def set_telegram_notifications(self, toggle):
@ -1100,23 +1053,17 @@ class Logger:
''' '''
Sends a Telegram message Sends a Telegram message
''' '''
try:
tg_credentials = credentials.get_credentials("telegram") tg_credentials = credentials.get_credentials("telegram")
send_text = f"https://api.telegram.org/bot{tg_credentials['token']}/sendMessage?chat_id={tg_credentials['chatid']}&parse_mode=Markdown&text={message}" send_text = f"https://api.telegram.org/bot{tg_credentials['token']}/sendMessage?chat_id={tg_credentials['chatid']}&parse_mode=Markdown&text={message}"
output = None output = None
if self.broker_config["telegram"] or ignore_config: if self.broker_config["telegram"] or ignore_config:
output = requests_get(send_text,timeout=5).json() #5 seconds timeout. This could also be a tunable. output = requests.get(send_text,timeout=5).json() #5 seconds timeout. This could also be a tunable.
if not output["ok"]: if not output["ok"]:
self.log_this(f"Error in send_tg_message: {output}") self.log_this(f"Error in send_tg_message: {output}")
return 1 return 1
return 0 return 0
except Exception as e:
self.log_this(f"Error in send_tg_message: {e}",1)
return 1
def log_order(self,message):
with open(f"logs/orders.log","a") as log_file:
log_file.write(time.strftime(f"[%Y/%m/%d %H:%M:%S] | {message}\n"))
def log_this(self,message,level=2,pair=None): def log_this(self,message,level=2,pair=None):
''' '''
@ -1138,16 +1085,21 @@ class Logger:
#Write to log file #Write to log file
with open(f"logs/{self.exchange_name}.log","a") as log_file: with open(f"logs/{self.exchange_name}.log","a") as log_file:
log_file.write(text+"\n") log_file.write(text+"\n")
log_file.close()
#Append to log list #Append to log list
self.log_list.append(text) self.log_list.append(text)
#Trim log list
self.log_list = self.log_list[-self.log_list_max_length:]
except Exception as e: except Exception as e:
print("Can't write log file") print("Can't write log file")
print(e) print(e)
if level<1: if level<1:
self.send_tg_message(f"{self.broker_config['exchange'].capitalize()} | {pair_data}{message}",ignore_config=level==-1) self.send_tg_message(f"{self.broker_config['exchange'].capitalize()} | {pair_data}{message}",ignore_config=level==-1)
return 0 return 0

1308
main.py

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,5 @@
from time import strftime import json
from json import dumps, load import time
class StatusHandler: class StatusHandler:
''' '''
@ -12,8 +12,7 @@ class StatusHandler:
"pair": f"{base}/{quote}", "pair": f"{base}/{quote}",
"take_profit_order": broker.get_empty_order(), "take_profit_order": broker.get_empty_order(),
"take_profit_price": 0.0, "take_profit_price": 0.0,
"safety_orders": [], "safety_order": broker.get_empty_order(),
"safety_orders_filled": 0,
"next_so_price": 0.0, "next_so_price": 0.0,
"order_size": 0.0, "order_size": 0.0,
"partial_profit": 0.0, "partial_profit": 0.0,
@ -24,7 +23,8 @@ class StatusHandler:
"quote_spent": 0.0, "quote_spent": 0.0,
"base_bought": 0.0, "base_bought": 0.0,
"so_amount": 0, "so_amount": 0,
"no_of_safety_orders": 0, "no_of_safety_orders": "",
"take_profit_price": "",
"safety_price_table": [], "safety_price_table": [],
"deal_uptime": 0.0, "deal_uptime": 0.0,
"total_uptime": 0.0, "total_uptime": 0.0,
@ -37,21 +37,18 @@ class StatusHandler:
"deal_start_time": 0, "deal_start_time": 0,
"stop_when_profit": False, "stop_when_profit": False,
"autoswitch": False, "autoswitch": False,
"liquidate_after_switch": False,
"old_long": {}, "old_long": {},
"pause_reason": "", "pause_reason": "",
"status_string": "", "status_string": "",
"deal_order_history": [] "deal_order_history": []
} }
self.status_file_path = f"status/{base}{quote}.status" self.status_file_path = f"status/{base}{quote}.status"
self.status_dictionary = self.default_status_dictionary.copy()
self.status_dictionary = {k: v for k, v in self.default_status_dictionary.items()} if status_dict is not None:
if status_dict: self.status_dictionary = {**self.status_dictionary, **status_dict}
self.status_dictionary.update(status_dict)
self.save_to_file() self.save_to_file()
def get_pair(self):
return self.status_dictionary["pair"]
def get_take_profit_order(self): def get_take_profit_order(self):
return self.status_dictionary["take_profit_order"] return self.status_dictionary["take_profit_order"]
@ -59,14 +56,8 @@ class StatusHandler:
def get_take_profit_price(self): def get_take_profit_price(self):
return self.status_dictionary["take_profit_price"] return self.status_dictionary["take_profit_price"]
def get_safety_orders(self): def get_safety_order(self):
""" return self.status_dictionary["safety_order"]
Returns the list of open safety orders
"""
return self.status_dictionary["safety_orders"]
def get_safety_orders_filled(self):
return self.status_dictionary["safety_orders_filled"]
def get_next_so_price(self): def get_next_so_price(self):
return self.status_dictionary["next_so_price"] return self.status_dictionary["next_so_price"]
@ -137,9 +128,6 @@ class StatusHandler:
def get_autoswitch(self): def get_autoswitch(self):
return self.status_dictionary["autoswitch"] return self.status_dictionary["autoswitch"]
def get_liquidate_after_switch(self):
return self.status_dictionary["liquidate_after_switch"]
def get_old_long(self): def get_old_long(self):
return self.status_dictionary["old_long"] return self.status_dictionary["old_long"]
@ -155,288 +143,167 @@ class StatusHandler:
def get_status_file_path(self): def get_status_file_path(self):
return self.status_file_path return self.status_file_path
def set_pair(self, trading_pair): def set_status_file_path(self, new_file_path):
self.pair = trading_pair
return 0
def set_status_file_path(self, new_file_path: str):
# if not isinstance(new_file_path, str):
# self.broker.logger.log_this(f"File path provided is not a string",1,self.get_pair())
# return 1
self.status_file_path = new_file_path self.status_file_path = new_file_path
return 0 return 0
def set_tp_order_id(self, order_id: str): def set_tp_order_id(self, order_id: str):
# if not isinstance(order_id, str):
# self.broker.logger.log_this(f"Order id provided is not a string",1,self.get_pair())
# return 1
self.status_dictionary["tp_order_id"] = order_id self.status_dictionary["tp_order_id"] = order_id
return 0 return 0
def set_take_profit_order(self, order): def set_take_profit_order(self, order):
#Validate order
self.status_dictionary["take_profit_order"] = order self.status_dictionary["take_profit_order"] = order
return 0 return 0
def set_take_profit_price(self, price: float): def set_take_profit_price(self, price: float):
# if not isinstance(price, float):
# self.broker.logger.log_this(f"Price provided is not a float",1,self.get_pair())
# return 1
self.status_dictionary["take_profit_price"] = price self.status_dictionary["take_profit_price"] = price
return 0 return 0
def set_so_order_id(self, order_id: str): def set_so_order_id(self, order_id: str):
# if not isinstance(order_id, str):
# self.broker.logger.log_this(f"Order id provided is not a string",1,self.get_pair())
# return 1
self.status_dictionary["so_order_id"] = order_id self.status_dictionary["so_order_id"] = order_id
return 0 return 0
def set_safety_orders(self, orders: list): def set_safety_order(self, order):
""" self.status_dictionary["safety_order"] = order
Replaces the whole safety orders list
"""
self.status_dictionary["safety_orders"] = orders
return 0
def set_safety_orders_filled(self, amount: int):
self.status_dictionary["safety_orders_filled"] = amount
return 0 return 0
def set_next_so_price(self, price: float): def set_next_so_price(self, price: float):
# if not isinstance(price, float):
# self.broker.logger.log_this(f"Price provided is not a float",1,self.get_pair())
# return 1
self.status_dictionary["next_so_price"] = price self.status_dictionary["next_so_price"] = price
return 0 return 0
def set_order_size(self, size: float): def set_order_size(self, size: float):
# if not isinstance(size, float):
# self.broker.logger.log_this(f"Size provided is not a float",1,self.get_pair())
# return 1
self.status_dictionary["order_size"] = size self.status_dictionary["order_size"] = size
return 0 return 0
def set_partial_profit(self, profit: float): def set_partial_profit(self, profit: float):
# if not isinstance(profit, float):
# self.broker.logger.log_this(f"Profit provided is not a float",1,self.get_pair())
# return 1
self.status_dictionary["partial_profit"] = profit self.status_dictionary["partial_profit"] = profit
return 0 return 0
def set_price(self, price: float): def set_price(self, price: float):
# if not isinstance(price, float):
# self.broker.logger.log_this(f"Price provided is not a float",1,self.get_pair())
# return 1
self.status_dictionary["price"] = price self.status_dictionary["price"] = price
return 0 return 0
def set_is_boosted(self, is_boosted: bool): def set_is_boosted(self, is_boosted: bool):
# if not isinstance(is_boosted, bool):
# self.broker.logger.log_this(f"is_boosted provided is not a bool",1,self.get_pair())
# return 1
self.status_dictionary["is_boosted"] = is_boosted self.status_dictionary["is_boosted"] = is_boosted
return 0 return 0
def set_is_short(self, is_short: bool): def set_is_short(self, is_short: bool):
# if not isinstance(is_short, bool):
# self.broker.logger.log_this(f"is_short provided is not a bool",1,self.get_pair())
# return 1
self.status_dictionary["is_short"] = is_short self.status_dictionary["is_short"] = is_short
return 0 return 0
def set_is_paused(self, is_paused: bool): def set_is_paused(self, is_paused: bool):
# if not isinstance(is_paused, bool):
# self.broker.logger.log_this(f"is_paused provided is not a bool",1,self.get_pair())
# return 1
self.status_dictionary["is_paused"] = is_paused self.status_dictionary["is_paused"] = is_paused
return 0 return 0
def set_quote_spent(self, quote_spent: float): def set_quote_spent(self, quote_spent: float):
# if not isinstance(quote_spent, float):
# self.broker.logger.log_this(f"quote_spent provided is not a float",1,self.get_pair())
# return 1
self.status_dictionary["quote_spent"] = quote_spent self.status_dictionary["quote_spent"] = quote_spent
return 0 return 0
def set_base_bought(self, base_bought: float): def set_base_bought(self, base_bought: float):
# if not isinstance(base_bought, float):
# self.broker.logger.log_this(f"base_bought provided is not a float",1,self.get_pair())
# return 1
self.status_dictionary["base_bought"] = base_bought self.status_dictionary["base_bought"] = base_bought
return 0 return 0
def set_so_amount(self, so_amount: int): def set_so_amount(self, so_amount: int):
# if not isinstance(so_amount, int):
# self.broker.logger.log_this(f"so_amount provided is not an integer",1,self.get_pair())
# return 1
self.status_dictionary["so_amount"] = so_amount self.status_dictionary["so_amount"] = so_amount
return 0 return 0
def set_no_of_safety_orders(self, number: int): def set_no_of_safety_orders(self, number: int):
# if not isinstance(number, int):
# self.broker.logger.log_this(f"number provided is not an integer",1,self.get_pair())
# return 1
self.status_dictionary["no_of_safety_orders"] = number self.status_dictionary["no_of_safety_orders"] = number
return 0 return 0
def set_safety_price_table(self, table: list): def set_safety_price_table(self, table: list):
# if not isinstance(table, list):
# self.broker.logger.log_this(f"table provided is not a list",1,self.get_pair())
# return 1
self.status_dictionary["safety_price_table"] = table self.status_dictionary["safety_price_table"] = table
return 0 return 0
def set_deal_uptime(self, uptime): def set_deal_uptime(self, uptime):
# if not isinstance(uptime, (int, float)): #if not isinstance(uptime, (int, float)):
# self.broker.logger.log_this(f"uptime provided is not a number",1,self.get_pair()) # raise ValueError("uptime be an integer or a float")
# return 1
self.status_dictionary["deal_uptime"] = uptime self.status_dictionary["deal_uptime"] = uptime
return 0 return 0
def set_total_uptime(self, uptime): def set_total_uptime(self, uptime):
# if not isinstance(uptime, (int, float)): #if not isinstance(uptime, (int, float)):
# self.broker.logger.log_this(f"uptime provided is not a number",1,self.get_pair()) # raise ValueError("uptime be an integer or a float")
# return 1
self.status_dictionary["total_uptime"] = uptime self.status_dictionary["total_uptime"] = uptime
return 0 return 0
def set_fees_paid_in_base(self, fees: float): def set_fees_paid_in_base(self, fees: float):
# if not isinstance(fees, float):
# self.broker.logger.log_this(f"value provided is not a float",1,self.get_pair())
# return 1
self.status_dictionary["fees_paid_in_base"] = fees self.status_dictionary["fees_paid_in_base"] = fees
return 0 return 0
def set_fees_paid_in_quote(self, fees: float): def set_fees_paid_in_quote(self, fees: float):
# if not isinstance(fees, float):
# self.broker.logger.log_this(f"value provided is not a float",1,self.get_pair())
# return 1
self.status_dictionary["fees_paid_in_quote"] = fees self.status_dictionary["fees_paid_in_quote"] = fees
return 0 return 0
def set_start_price(self, price: float): def set_start_price(self, price: float):
# if not isinstance(price, float):
# self.broker.logger.log_this(f"value provided is not a float",1,self.get_pair())
# return 1
self.status_dictionary["start_price"] = price self.status_dictionary["start_price"] = price
return 0 return 0
def set_tp_mode(self, mode: int): def set_tp_mode(self, mode: int):
# if not isinstance(mode, int):
# self.broker.logger.log_this(f"value provided is not an integer",1,self.get_pair())
# return 1
self.status_dictionary["tp_mode"] = mode self.status_dictionary["tp_mode"] = mode
return 0 return 0
def set_profit_table(self, table: list): def set_profit_table(self, table: list):
# if not isinstance(table, list):
# self.broker.logger.log_this(f"value provided is not a list",1,self.get_pair())
# return 1
self.status_dictionary["profit_table"] = table self.status_dictionary["profit_table"] = table
return 0 return 0
def set_start_time(self, time): def set_start_time(self, time):
# if not isinstance(time, (int, float)): #if not isinstance(uptime, (int, float)):
# self.broker.logger.log_this(f"value provided is not a number",1,self.get_pair()) # raise ValueError("uptime be an integer or a float")
# return 1
self.status_dictionary["start_time"] = time self.status_dictionary["start_time"] = time
return 0 return 0
def set_deal_start_time(self, time): def set_deal_start_time(self, time):
# if not isinstance(time, (int, float)): #if not isinstance(uptime, (int, float)):
# self.broker.logger.log_this(f"value provided is not a number",1,self.get_pair()) # raise ValueError("uptime be an integer or a float")
# return 1
self.status_dictionary["deal_start_time"] = time self.status_dictionary["deal_start_time"] = time
return 0 return 0
def set_stop_when_profit(self, stop: bool): def set_stop_when_profit(self, stop: bool):
# if not isinstance(stop, bool):
# self.broker.logger.log_this(f"value provided is not a boolean",1,self.get_pair())
# return 1
self.status_dictionary["stop_when_profit"] = stop self.status_dictionary["stop_when_profit"] = stop
return 0 return 0
def set_autoswitch(self, switch: bool): def set_autoswitch(self, switch: bool):
# if not isinstance(switch, bool):
# self.broker.logger.log_this(f"value provided is not a boolean",1,self.get_pair())
# return 1
self.status_dictionary["autoswitch"] = switch self.status_dictionary["autoswitch"] = switch
return 0 return 0
def set_liquidate_after_switch(self, switch: bool):
# if not isinstance(switch, bool):
# self.broker.logger.log_this(f"value provided is not a boolean",1,self.get_pair())
# return 1
self.status_dictionary["liquidate_after_switch"] = switch
return 0
def set_old_long(self, old_long: dict): def set_old_long(self, old_long: dict):
# if not isinstance(old_long, dict):
# self.broker.logger.log_this(f"value provided is not a dictionary",1,self.get_pair())
# return 1
self.status_dictionary["old_long"] = old_long self.status_dictionary["old_long"] = old_long
return 0 return 0
def set_pause_reason(self, reason: str): def set_pause_reason(self, reason: str):
# if not isinstance(reason, str):
# self.broker.logger.log_this(f"value provided is not a string",1,self.get_pair())
# return 1
self.status_dictionary["pause_reason"] = reason self.status_dictionary["pause_reason"] = reason
return 0 return 0
def set_status_string(self, string: str): def set_status_string(self, string: str):
# if not isinstance(string, str):
# self.broker.logger.log_this(f"value provided is not a string",1,self.get_pair())
# return 1
self.status_dictionary["status_string"] = string self.status_dictionary["status_string"] = string
return 0 return 0
def set_deal_order_history(self, deal_history: list): def set_deal_order_history(self, deal_history: list):
# if not isinstance(deal_history, list):
# self.broker.logger.log_this(f"value provided is not a list",1,self.get_pair())
# return 1
self.status_dictionary["deal_order_history"] = deal_history self.status_dictionary["deal_order_history"] = deal_history
return 0 return 0
def add_safety_order(self, order):
"""
Appends a newly-created safety order to the internal list
"""
self.status_dictionary["safety_orders"].append(order)
return 0
def remove_safety_order_by_id(self, order_id: str):
"""
Removes an order from the list (mostly used when that order is filled or canceled)
"""
orders = self.get_safety_orders()
self.status_dictionary["safety_orders"] = [order for order in orders if order["id"] != order_id]
return 0
def clear_deal_order_history(self): def clear_deal_order_history(self):
self.status_dictionary["deal_order_history"] = [] self.status_dictionary["deal_order_history"] = []
return 0 return 0
def update_deal_order_history(self, new_deal: dict, note: str = ""): def update_deal_order_history(self, new_deal: dict):
# if not isinstance(new_deal, dict): self.status_dictionary["deal_order_history"].append(new_deal)
# self.broker.logger.log_this(f"value provided is not a dict",1,self.get_pair())
id = new_deal["id"] if "id" in new_deal else None
self.status_dictionary["deal_order_history"].append(f"{note} - {id}")
return 0 return 0
def save_to_file(self, file_path = None, is_backup = False): def save_to_file(self, file_path = None, is_backup = False):
if file_path is None: if file_path is None:
file_path = self.status_file_path file_path = self.status_file_path
if is_backup: if is_backup:
try: try:
with open(strftime(f"{file_path}_%Y-%m-%d_%H:%M:%S.json"), "w") as f: with open(time.strftime(f"{file_path}_%Y-%m-%d_%H:%M:%S.json"), "w") as f:
f.write(dumps(self.status_dictionary, indent=4)) f.write(json.dumps(self.status_dictionary, indent=4))
except Exception as e: except Exception as e:
self.broker.logger.log_this(f"Error creating status backup file: {e}",1) self.broker.logger.log_this(f"Error creating status backup file: {e}",1)
try: try:
with open(file_path, "w") as f: with open(file_path, "w") as f:
f.write(dumps(self.status_dictionary, indent=4)) f.write(json.dumps(self.status_dictionary, indent=4))
return 0 return 0
except Exception as e: except Exception as e:
self.broker.logger.log_this(f"Error saving status to file: {file_path}: {e}",1) self.broker.logger.log_this(f"Error saving status to file: {file_path}: {e}",1)
@ -447,7 +314,7 @@ class StatusHandler:
file_path = self.status_file_path file_path = self.status_file_path
try: try:
with open(file_path, "r") as f: with open(file_path, "r") as f:
self.status_dictionary = {**self.default_status_dictionary, **load(f)} self.status_dictionary = {**self.default_status_dictionary, **json.load(f)}
return 0 return 0
except Exception as e: except Exception as e:
self.broker.logger.log_this(f"Error loading status from file: {file_path}: {e}",1) self.broker.logger.log_this(f"Error loading status from file: {file_path}: {e}",1)
@ -460,8 +327,6 @@ class StatusHandler:
''' '''
Validates every key in the dictionary and then sets the status dictionary Validates every key in the dictionary and then sets the status dictionary
''' '''
# if not isinstance(dictionary, dict):
# self.broker.logger.log_this(f"status_dictionary provided is not a dictionary",1,self.get_pair())
# return 1
self.status_dictionary = dictionary self.status_dictionary = dictionary
return 0 return 0

View File

@ -1,25 +1,32 @@
Mandatory: Mandatory:
========= =========
0. Stats webpage. 1. Stats webpage.
1. Maintain local orderbooks for each trading pair, which enables: 2. Maintain local orderbooks for each trading pair, which enables:
2a. Smart order pricing: Prioritization of fill speed over instant profit or vice versa 2a. Smart order pricing: Prioritization of fill speed over instant profit or vice versa
2. Proper handling of order price too high/low in OKX (rare, it happens when under heavy volatility). 3. Consolidate vocabulary (trader, pair and bot; instance & trader)
3. API documentation. 4. Base add for short traders.
4. Implement api key hashing. 5. Proper handling of order price too high/low in OKX (rare, it happens when under heavy volatility).
5. Dockerize. 6. Multiple safety orders open at the same time (to catch big volatility spikes more effectively)
6. Earn should be integrated into the instance, in order to be able to invest the idle funds from the short traders. 7. Things that should be objects (it's not 1994):
* Orders.
* Config (parameter validation remains to be implemented).
* Status (parameter validation remains to be implemented).
8. Implement the ability to add safety orders to a short trader depending on the amount of free funds available, not just any number of orders.
9. API documentation.
10. Implement api key hashing.
Would be nice to have: Would be nice to have:
===================== =====================
0. Trader order: alphabetical; by uptime; by safety orders, by percentage_to_completion. (Although this may be more suitable for the web and mobile apps) 0. Trader order: alphabetical; by uptime; by safety orders, by percentage_to_completion. (Although this may be more suitable for the web and mobile apps)
1. Local implementation of amount_to_precision, cost_to_precision and price_to_precision. (Unless the plan is to continue to use CCXT forever) 1. Local implementation of amount_to_precision, cost_to_precision and price_to_precision. (Unless the plan is to continue to use CCXT forever)
2. Instead of cancelling and resending the take profit order, edit it (Kucoin only supports editing on high frequency orders) 2. Instead of cancelling and resending the take profit order, you could just edit it (Kucoin only supports editing on high frequency orders)
3. When autoswitching to long, instead of using a big market order, the last safety order should be a sell order of all the available funds. 3. Round-robin trading pairs: Instead of a fixed list of trading pairs, after n closed deals the trader is terminated and a new one spawns, picking the trading pair
4. Round-robin trading pairs: Instead of a fixed list of trading pairs, after n closed deals the trader is terminated and a new one spawns, picking the trading pair
from a pre-populated list (the trading pairs can be selected by using Yang-Zhang, Parkinson or another volatility indicator) from a pre-populated list (the trading pairs can be selected by using Yang-Zhang, Parkinson or another volatility indicator)
This could be very benefitial, since it limits the long time commitment to a small list of trading pairs, enabling the instance to react to market trends very This could be very benefitial, since it limits the long time commitment to a small list of trading pairs, enabling the instance to react to market trends very
rapidly. rapidly.
4. Earn should also use funds from short traders.
4b. Should Earn be integrated to the instance?
Maybe it's a good idea?: Maybe it's a good idea?:

1398
trader.py

File diff suppressed because it is too large Load Diff

View File

@ -10,7 +10,7 @@ with open(f"../configs/{sys.argv[1]}.json") as k:
pwd = config["password"] if "password" in config else "" pwd = config["password"] if "password" in config else ""
exch = sys.argv[1] exch = sys.argv[1]
if exch=="okex": if exch=="okex":
exch="okx" exch="okex5"
exchange_class = getattr(ccxt, sys.argv[1]) exchange_class = getattr(ccxt, sys.argv[1])
exchange = exchange_class({ exchange = exchange_class({
"apiKey": config["key"], "apiKey": config["key"],

View File

@ -11,12 +11,6 @@ try:
api_key = credentials.get_credentials("testnet_api_key")["key"] api_key = credentials.get_credentials("testnet_api_key")["key"]
base_url = credentials.get_url("testnet") #type: ignore base_url = credentials.get_url("testnet") #type: ignore
exchanges = {"Binance":"/binance"} exchanges = {"Binance":"/binance"}
elif sys.argv[1]=="--local_testnet":
is_testnet = True
string_to_add = "LOCAL TESTNET "
api_key = credentials.get_credentials("local_testnet_api_key")["key"]
base_url = credentials.get_url("local_testnet") #type: ignore
exchanges = {"Binance":":5001"}
elif sys.argv[1]=="--mainnet": elif sys.argv[1]=="--mainnet":
is_testnet = False is_testnet = False
string_to_add = "MAINNET " string_to_add = "MAINNET "
@ -43,8 +37,6 @@ INSTANCE
10) edit_call_wait_time 11) reload_markets 12) fetch_full_log 10) edit_call_wait_time 11) reload_markets 12) fetch_full_log
13) paused_traders 14) fetch_log 15) edit_cooldown_multiplier 13) paused_traders 14) fetch_log 15) edit_cooldown_multiplier
16) get_balance 17) cancel_global_last_call 16) get_balance 17) cancel_global_last_call
18) mod_default_order_size 19) toggle_log_orders
20) refresh_log_cache
EARN EARN
31) toggle_pause 32) get_step_size 33) set_step_size 31) toggle_pause 32) get_step_size 33) set_step_size
@ -53,7 +45,7 @@ EARN
39) set_time_between_redemptions 40) get_minimum_amount_in_trading_account 39) set_time_between_redemptions 40) get_minimum_amount_in_trading_account
41) set_minimum_amount_in_trading_account 42) get_last_subscription 41) set_minimum_amount_in_trading_account 42) get_last_subscription
43) get_last_redemption 44) get_total_balance 43) get_last_redemption 44) get_total_balance
45) get_global_status 46) subscribe 47) redeem 45) get_global_status
TRADERS TRADERS
51) worker_status 52) get_all_worker_status 51) worker_status 52) get_all_worker_status
@ -63,10 +55,8 @@ TRADERS
62) mod_tp_level 63) last_call 64) deferred_last_call 62) mod_tp_level 63) last_call 64) deferred_last_call
65) toggle_pause 66) toggle_cleanup 67) toggle_autoswitch 65) toggle_pause 66) toggle_cleanup 67) toggle_autoswitch
68) toggle_check_old_long_price 69) switch_quote_currency 68) toggle_check_old_long_price 69) switch_quote_currency
70) view_old_long 71) switch_price 72) reload_trader_config 70) reload_safety_order 71) view_old_long 72) switch_price
73) toggle_liquidate_after_switch 74) base_add_calculation 73) reload_trader_config
75) mod_concurrent_safety_orders 76) force_trader_close
77) mod_order_size
98) Change broker 99) Exit 98) Change broker 99) Exit
''' '''
@ -328,33 +318,6 @@ if __name__=="__main__":
print(json.loads(requests.post(url, headers=headers).content)) print(json.loads(requests.post(url, headers=headers).content))
input("Press ENTER to continue ") input("Press ENTER to continue ")
elif command==18:
print("mod_default_order_size modifies the default order size that is used when creating a trader")
print(f"Current value is {None}")
print("The input value can be an integer or a float")
new_default_order_size = input("New default order size: ")
if not validate_float_or_int(new_default_order_size):
print("The input is invalid")
break
if input("Proceed? (Y/n) ") in ["Y","y",""]:
url = f"{base_url}{port}/mod_default_order_size"
parameters = {"amount": new_default_order_size}
print(json.loads(requests.post(url, headers=headers, json=parameters).content))
input("Press ENTER to continue ")
elif command==19:
print("toggle_log_orders turns on or off the logging of orders")
if input("Proceed? (Y/n) ") in ["Y","y",""]:
url = f"{base_url}{port}/toggle_log_orders"
print(json.loads(requests.post(url, headers=headers).content))
input("Press ENTER to continue ")
elif command==20:
print("refresh_log_cache refreshes the log cache")
if input("Proceed? (Y/n) ") in ["Y","y",""]:
url = f"{base_url}{port}/refresh_log_cache"
print(json.loads(requests.post(url, headers=headers).content))
input("Press ENTER to continue ")
###################### ######################
######## EARN ######## ######## EARN ########
@ -482,36 +445,6 @@ if __name__=="__main__":
print(json.loads(requests.get(url,headers=earn_headers).content)) print(json.loads(requests.get(url,headers=earn_headers).content))
input("Press ENTER to continue ") input("Press ENTER to continue ")
elif command==46:
print("subscribe forces funds subscription")
amount_to_subscribe = input("Enter the amount to subscribe: ")
if not validate_float_or_int(amount_to_subscribe):
print("The input is invalid")
break
if input("Proceed? (Y/n) ") in ["Y","y",""]:
url = f"{base_url}/earn/subscribe"
parameters = {
"broker": earn_broker,
"amount": amount_to_subscribe}
print(json.loads(requests.post(url,headers=earn_headers, json=parameters).content))
input("Press ENTER to continue ")
elif command==47:
print("redeem forces funds redemption")
amount_to_redeem = input("Enter the amount to redeem: ")
if not validate_float_or_int(amount_to_redeem):
print("The input is invalid")
break
if input("Proceed? (Y/n) ") in ["Y","y",""]:
url = f"{base_url}/earn/redeem"
parameters = {
"broker": earn_broker,
"amount": amount_to_redeem}
print(json.loads(requests.post(url,headers=earn_headers, json=parameters).content))
input("Press ENTER to continue ")
###################### ######################
####### TRADER ####### ####### TRADER #######
###################### ######################
@ -582,6 +515,10 @@ if __name__=="__main__":
print("In order for the importing to be successful, a status file must exist in the status directory ") print("In order for the importing to be successful, a status file must exist in the status directory ")
print("and the take profit order must be open.") print("and the take profit order must be open.")
trading_pair = input("Input trader in the format BASE/QUOTE: ").upper() trading_pair = input("Input trader in the format BASE/QUOTE: ").upper()
tp_id_input = input("Input take profit order id to use (if any)")
forced_tp_id = None if tp_id_input=="" else tp_id_input
so_id_input = input("Input safety order id to use (if any)")
forced_so_id = None if so_id_input=="" else so_id_input
if not validate_pair(trading_pair): if not validate_pair(trading_pair):
print("The input is invalid") print("The input is invalid")
@ -590,7 +527,9 @@ if __name__=="__main__":
url = f"{base_url}{port}/import_pair" url = f"{base_url}{port}/import_pair"
base,quote = trading_pair.split("/") base,quote = trading_pair.split("/")
parameters = {"base": base, parameters = {"base": base,
"quote": quote} "quote": quote,
"forced_tp_id": forced_tp_id,
"forced_so_id": forced_so_id}
print(json.loads(requests.post(url, headers=headers, json=parameters).content)) print(json.loads(requests.post(url, headers=headers, json=parameters).content))
input("Press ENTER to continue ") input("Press ENTER to continue ")
@ -813,6 +752,20 @@ if __name__=="__main__":
input("Press ENTER to continue ") input("Press ENTER to continue ")
elif command==70: elif command==70:
print("reload_safety_order reloads the safety order to the reader using the order id present in the status dictionary")
trading_pair = input("Input trader in the format BASE/QUOTE: ").upper()
if not validate_pair(trading_pair):
print("The input is invalid")
break
if input("Proceed? (Y/n) ") in ["Y","y",""]:
url = f"{base_url}{port}/reload_safety_order"
base,quote = trading_pair.split("/")
parameters = {"base": base,
"quote": quote}
print(json.loads(requests.post(url, headers=headers, json=parameters).content))
input("Press ENTER to continue ")
elif command==71:
print("Views the old_long information") print("Views the old_long information")
trading_pair = input("Input trader in the format BASE/QUOTE: ").upper() trading_pair = input("Input trader in the format BASE/QUOTE: ").upper()
if not validate_pair(trading_pair): if not validate_pair(trading_pair):
@ -825,7 +778,7 @@ if __name__=="__main__":
print(json.loads(requests.get(url,headers=headers).content)) print(json.loads(requests.get(url,headers=headers).content))
input("Press ENTER to continue ") input("Press ENTER to continue ")
elif command==71: elif command==72:
print("Returns the price target to reach to switch to long mode") print("Returns the price target to reach to switch to long mode")
trading_pair = input("Input trader in the format BASE/QUOTE: ").upper() trading_pair = input("Input trader in the format BASE/QUOTE: ").upper()
if not validate_pair(trading_pair): if not validate_pair(trading_pair):
@ -837,7 +790,7 @@ if __name__=="__main__":
print(json.loads(requests.get(url,headers=headers).content)) print(json.loads(requests.get(url,headers=headers).content))
input("Press ENTER to continue ") input("Press ENTER to continue ")
elif command==72: elif command==73:
print("Reloads from disk the configuration file of a trader") print("Reloads from disk the configuration file of a trader")
trading_pair = input("Input trader in the format BASE/QUOTE: ").upper() trading_pair = input("Input trader in the format BASE/QUOTE: ").upper()
if not validate_pair(trading_pair): if not validate_pair(trading_pair):
@ -850,83 +803,3 @@ if __name__=="__main__":
"quote": quote} "quote": quote}
print(json.loads(requests.post(url, headers=headers, json=parameters).content)) print(json.loads(requests.post(url, headers=headers, json=parameters).content))
input("Press ENTER to continue ") input("Press ENTER to continue ")
elif command==73:
print("toggle_liquidate_after_switch enables or disables the liquidation after an automatic switch to long of a short trader")
print("This is only valid in a short trader, of course.")
trading_pair = input("Input trader in the format BASE/QUOTE: ").upper()
if not validate_pair(trading_pair):
print("The input is invalid")
break
if input("Proceed? (Y/n) ") in ["Y","y",""]:
url = f"{base_url}{port}/toggle_liquidate_after_switch"
base,quote = trading_pair.split("/")
parameters = {"base": base,
"quote": quote}
print(json.loads(requests.post(url, headers=headers, json=parameters).content))
input("Press ENTER to continue ")
elif command==74:
print("Returns the amount of safety orders that can be added to a short trader with the available funds")
trading_pair = input("Input trader in the format BASE/QUOTE: ").upper()
if not validate_pair(trading_pair):
print("The input is invalid")
break
if input("Proceed? (Y/n) ") in ["Y","y",""]:
base,quote = trading_pair.split("/")
url = f"{base_url}{port}/base_add_so_calculation?base={base}&quote={quote}"
print(json.loads(requests.get(url,headers=headers).content))
input("Press ENTER to continue ")
elif command==75:
print("mod_concurrent_safety_orders modifies the amount of safety orders opened at the same time")
trading_pair = input("Input trader in the format BASE/QUOTE: ").upper()
new_amount = input("Desired amount of orders: ")
if not validate_pair(trading_pair):
print("The input is invalid")
break
if not validate_int(new_amount):
print("The amount entered is invalid")
break
if input("Proceed? (Y/n) ") in ["Y","y",""]:
url = f"{base_url}{port}/mod_concurrent_safety_orders"
base,quote = trading_pair.split("/")
parameters = {"base": base,
"quote": quote,
"amount": new_amount}
print(json.loads(requests.post(url, headers=headers, json=parameters).content))
input("Press ENTER to continue ")
elif command==76:
print("force_trader_close forces a trader to close the current position")
trading_pair = input("Input trader in the format BASE/QUOTE: ").upper()
if not validate_pair(trading_pair):
print("The input is invalid")
break
if input("Proceed? (Y/n) ") in ["Y","y",""]:
url = f"{base_url}{port}/force_trader_close"
base,quote = trading_pair.split("/")
parameters = {"base": base,
"quote": quote}
print(json.loads(requests.post(url, headers=headers, json=parameters).content))
input("Press ENTER to continue ")
elif command==77:
print("mod_order_size modifies the initial order size of a trader")
print("The change impacts as soon as the trader starts a new deal")
trading_pair = input("Input trader in the format BASE/QUOTE: ").upper()
amount = input("Desired order size: ")
if not validate_pair(trading_pair):
print("The input is invalid")
break
if not validate_float_or_int(amount):
print("The amount entered is invalid")
break
if input("Proceed? (Y/n) ") in ["Y","y",""]:
url = f"{base_url}{port}/mod_order_size"
base,quote = trading_pair.split("/")
parameters = {"base": base,
"quote": quote,
"amount": amount}
print(json.loads(requests.post(url, headers=headers, json=parameters).content))
input("Press ENTER to continue ")

View File

@ -1,44 +1,41 @@
import sqlite3 import sqlite3
import sys
import datetime import datetime
import time import time
import ccxt
import credentials
import calendar import calendar
import requests
import logging import logging
import threading
import os
from contextlib import contextmanager
from flask import Flask, jsonify, request from flask import Flask, jsonify, request
from waitress import serve from waitress import serve
cache_requests = True if len(sys.argv)>1 and sys.argv[1]=="--cache_requests" else False
profits_database = "../profits/profits_database.db" profits_database = "../profits/profits_database.db"
_local_storage = threading.local() hashes_db = {"fetch_last_n_deals":0,
"fetch_last_n_deals_without_history":0,
"fetch_full_log":0,
"fetch_log":0,
"daily_totals":0,
"daily_totals_by_pair":0,
"monthly_totals":0,
"monthly_totals_by_pair":0,
"get_averages":0,
"total_profit":0,
"total_profit_by_pair":0}
def get_db_connection():
current_time = time.time()
if not hasattr(_local_storage, 'connection') or not hasattr(_local_storage, 'created_at') or (current_time - _local_storage.created_at) > 3600: # Reconnect every hour def get_market_caps(limit):
if hasattr(_local_storage, 'connection'): api_key = credentials.get_credentials("CMC")["key"]
try: url = f"https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY={api_key}&convert=USD&limit={limit}"
_local_storage.connection.close() return requests.get(url).json()["data"]
except:
pass
_local_storage.connection = sqlite3.connect(profits_database, check_same_thread=False)
_local_storage.connection.row_factory = sqlite3.Row
_local_storage.created_at = current_time
return _local_storage.connection
@contextmanager
def db_cursor():
conn = get_db_connection()
cur = conn.cursor()
try:
yield cur
except Exception:
conn.rollback()
raise
def load_keys_from_db(file_name): def load_keys_from_db(file_name):
#valid_keys = []
connection = sqlite3.connect(file_name) connection = sqlite3.connect(file_name)
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("SELECT * FROM credentials_table") cursor.execute("SELECT * FROM credentials_table")
@ -46,20 +43,18 @@ def load_keys_from_db(file_name):
connection.close() connection.close()
valid_keys = [line[1] for line in data] valid_keys = [line[1] for line in data]
#for line in data:
# valid_keys.append(line[1])
return valid_keys return valid_keys
def get_valid_keys():
if not hasattr(get_valid_keys, '_keys'):
get_valid_keys._keys = load_keys_from_db("api_credentials.db")
return get_valid_keys._keys
def profit_report(): def profit_report():
##Queries ##Queries
connection = sqlite3.connect(profits_database)
cursor = connection.cursor()
#Last 60 days query #Last 60 days query
with db_cursor() as cursor:
cursor.execute("""SELECT strftime('%Y-%m-%d', timestamp, 'unixepoch', '-3 hours') AS day_utc3, cursor.execute("""SELECT strftime('%Y-%m-%d', timestamp, 'unixepoch', '-3 hours') AS day_utc3,
SUM(amount) AS total_amount SUM(amount) AS total_amount
FROM profits_table FROM profits_table
@ -68,21 +63,19 @@ def profit_report():
ORDER BY day_utc3;""") ORDER BY day_utc3;""")
last_60_days_rows = cursor.fetchall() last_60_days_rows = cursor.fetchall()
#Last 30 days query #Last 30 days query
with db_cursor() as cursor: #cursor.execute("""SELECT strftime('%Y-%m-%d', timestamp, 'unixepoch', '-3 hours') AS day_utc3,
cursor.execute("""SELECT strftime('%Y-%m-%d', timestamp, 'unixepoch', '-3 hours') AS day_utc3, cursor.execute("""SELECT strftime('%Y-%m-%d', timestamp, 'unixepoch', '-3 hours') AS day_utc3,
SUM(amount) AS total_amount SUM(amount) AS total_amount
FROM profits_table FROM profits_table
WHERE strftime('%s', 'now') - timestamp <= 30 * 24 * 60 * 60 -- 30 days in seconds;""") WHERE strftime('%s', 'now') - timestamp <= 30 * 24 * 60 * 60 -- 30 days in seconds;""")
last_30_days = cursor.fetchall() last_30_days = cursor.fetchall()
#Last 7 days query #Last 7 days query
with db_cursor() as cursor:
cursor.execute("""SELECT strftime('%Y-%m-%d', timestamp, 'unixepoch', '-3 hours') AS day_utc3, cursor.execute("""SELECT strftime('%Y-%m-%d', timestamp, 'unixepoch', '-3 hours') AS day_utc3,
SUM(amount) AS total_amount SUM(amount) AS total_amount
FROM profits_table FROM profits_table
WHERE strftime('%s', 'now') - timestamp <= 7 * 24 * 60 * 60 -- 7 days in seconds;""") WHERE strftime('%s', 'now') - timestamp <= 7 * 24 * 60 * 60 -- 7 days in seconds;""")
last_7_days = cursor.fetchall() last_7_days = cursor.fetchall()
#Last n months query #Last n months query
with db_cursor() as cursor:
cursor.execute("""SELECT strftime('%Y-%m', timestamp, 'unixepoch', '-3 hours') AS year_month_utc3, cursor.execute("""SELECT strftime('%Y-%m', timestamp, 'unixepoch', '-3 hours') AS year_month_utc3,
SUM(amount) AS total_amount SUM(amount) AS total_amount
FROM profits_table FROM profits_table
@ -91,15 +84,14 @@ def profit_report():
ORDER BY year_month_utc3;""") ORDER BY year_month_utc3;""")
last_n_months_rows = cursor.fetchall() last_n_months_rows = cursor.fetchall()
#Yearly totals #Yearly totals
# cursor.execute("""SELECT strftime('%Y', timestamp, 'unixepoch', '-3 hours') AS year_utc3, cursor.execute("""SELECT strftime('%Y', timestamp, 'unixepoch', '-3 hours') AS year_utc3,
# SUM(amount) AS total_amount SUM(amount) AS total_amount
# FROM profits_table FROM profits_table
# WHERE strftime('%s', 'now') - timestamp <= 24 * 365 * 60 * 60 -- 365 days in seconds WHERE strftime('%s', 'now') - timestamp <= 24 * 365 * 60 * 60 -- 365 days in seconds
# GROUP BY year_utc3 GROUP BY year_utc3
# ORDER BY year_utc3;""") ORDER BY year_utc3;""")
# yearly_totals = cursor.fetchall() yearly_totals = cursor.fetchall()
#Per exchange #Per exchange
with db_cursor() as cursor:
cursor.execute("""SELECT cursor.execute("""SELECT
exchange_name, exchange_name,
CASE CASE
@ -118,6 +110,9 @@ def profit_report():
exchange_name, month_group;""") exchange_name, month_group;""")
per_exchange = cursor.fetchall() per_exchange = cursor.fetchall()
#Close db
cursor.close()
#Projection calculation #Projection calculation
days_in_month = calendar.monthrange(datetime.date.today().year, datetime.date.today().month)[1] days_in_month = calendar.monthrange(datetime.date.today().year, datetime.date.today().month)[1]
@ -132,17 +127,16 @@ def profit_report():
okex_amount = 0 okex_amount = 0
for row in per_exchange: for row in per_exchange:
exchange_name = row[0].strip().lower() if row[0]=="binance":
if exchange_name=="binance":
if row[1]=="This Month": if row[1]=="This Month":
binance_amount = row[2] binance_amount = row[2]
elif exchange_name=="gateio": elif row[0]=="gateio":
if row[1]=="This Month": if row[1]=="This Month":
gateio_amount = row[2] gateio_amount = row[2]
elif exchange_name=="kucoin": elif row[0]=="kucoin":
if row[1]=="This Month": if row[1]=="This Month":
kucoin_amount = row[2] kucoin_amount = row[2]
elif exchange_name=="okex": elif row[0]=="okex":
if row[1]=="This Month": if row[1]=="This Month":
okex_amount = row[2] okex_amount = row[2]
@ -174,24 +168,27 @@ def profit_report():
"Total profit": total_amount} "Total profit": total_amount}
def query_total_profit(pair=None): def query_total_profit(pair=None):
''' '''
Returns total profit of the trading pair. Returns total profit of the trading pair.
If no pair specified, returns the grand total of all pairs. If no pair specified, returns the grand total of all pairs.
''' '''
connection = sqlite3.connect(profits_database)
cursor = connection.cursor()
if pair is None: if pair is None:
query = "SELECT SUM(amount) AS total_profit FROM profits_table" query = "SELECT SUM(amount) AS total_profit FROM profits_table"
with db_cursor() as cursor:
cursor.execute(query) cursor.execute(query)
connection.close()
query_result = cursor.fetchall() query_result = cursor.fetchall()
return query_result[0][0] return query_result[0][0]
else: else:
query = """SELECT pair, SUM(amount) AS total_profit query = """SELECT pair, SUM(amount) AS total_profit
FROM profits_table FROM profits_table
GROUP BY pair;""" GROUP BY pair;"""
with db_cursor() as cursor:
cursor.execute(query) cursor.execute(query)
connection.close()
query_result = cursor.fetchall() query_result = cursor.fetchall()
for item in query_result: for item in query_result:
if item[0].replace("/","")==pair: if item[0].replace("/","")==pair:
@ -199,11 +196,13 @@ def query_total_profit(pair=None):
return 0 return 0
def daily_and_monthly_totals() -> tuple[float, float]: def daily_and_monthly_totals():
''' '''
Returns a tuple with the current day and the current month's total profit. Returns a tuple with the current day and the current month's total profit.
''' '''
#Connect to db
connection = sqlite3.connect(profits_database)
cursor = connection.cursor()
now = datetime.datetime.now() now = datetime.datetime.now()
# Create a datetime object for the start of the day # Create a datetime object for the start of the day
@ -214,16 +213,15 @@ def daily_and_monthly_totals() -> tuple[float, float]:
start_of_day_unix = int(time.mktime(start_of_day.timetuple())) start_of_day_unix = int(time.mktime(start_of_day.timetuple()))
start_of_month_unix = int(time.mktime(start_of_month.timetuple())) start_of_month_unix = int(time.mktime(start_of_month.timetuple()))
query = """SELECT query = f"""SELECT * FROM profits_table
COALESCE(SUM(CASE WHEN timestamp >= :day THEN amount END),0) AS daily_total, WHERE timestamp >= {start_of_month_unix}
COALESCE(SUM(CASE WHEN timestamp >= :month THEN amount END),0) AS monthly_total ORDER BY timestamp DESC;"""
FROM profits_table; cursor.execute(query)
""" query_result = cursor.fetchall()
with db_cursor() as cur: connection.close()
cur.execute(query, {"day": start_of_day_unix, "month": start_of_month_unix})
row = cur.fetchone() monthly_total = sum([item[2] for item in query_result])
daily_total = float(row["daily_total"]) daily_total = sum([item[2] for item in query_result if item[0]>=start_of_day_unix])
monthly_total = float(row["monthly_total"])
return (daily_total, monthly_total) return (daily_total, monthly_total)
@ -233,6 +231,9 @@ def query_daily_totals(pair=None):
Returns a dictionary of daily totals of the trading pair. Returns a dictionary of daily totals of the trading pair.
If no pair specified, returns the totals of all pairs. If no pair specified, returns the totals of all pairs.
''' '''
#Connect to db
connection = sqlite3.connect(profits_database)
cursor = connection.cursor()
result = {} result = {}
@ -241,9 +242,9 @@ def query_daily_totals(pair=None):
SUM(amount) AS total_profit SUM(amount) AS total_profit
FROM profits_table FROM profits_table
GROUP BY day_utc3;""" GROUP BY day_utc3;"""
with db_cursor() as cursor:
cursor.execute(query) cursor.execute(query)
query_result = cursor.fetchall() query_result = cursor.fetchall()
connection.close()
for item in query_result: for item in query_result:
result[item[0]] = item[1] result[item[0]] = item[1]
else: else:
@ -251,9 +252,9 @@ def query_daily_totals(pair=None):
SUM(amount) AS total_profit SUM(amount) AS total_profit
FROM profits_table FROM profits_table
GROUP BY pair, day_utc3;""" GROUP BY pair, day_utc3;"""
with db_cursor() as cursor:
cursor.execute(query) cursor.execute(query)
query_result = cursor.fetchall() query_result = cursor.fetchall()
connection.close()
for item in query_result: for item in query_result:
if item[0].replace("/","")==pair: if item[0].replace("/","")==pair:
result[item[1]] = item[2] result[item[1]] = item[2]
@ -265,6 +266,9 @@ def query_monthly_totals(pair=None):
Returns a dictionary of monthly totals of the trading pair. Returns a dictionary of monthly totals of the trading pair.
If no pair specified, returns the totals of all pairs. If no pair specified, returns the totals of all pairs.
''' '''
#Connect to db
connection = sqlite3.connect(profits_database)
cursor = connection.cursor()
result = {} result = {}
@ -273,19 +277,19 @@ def query_monthly_totals(pair=None):
SUM(amount) AS total_profit SUM(amount) AS total_profit
FROM profits_table FROM profits_table
GROUP BY month;""" GROUP BY month;"""
with db_cursor() as cursor:
cursor.execute(query) cursor.execute(query)
query_result = cursor.fetchall() query_result = cursor.fetchall()
connection.close()
for item in query_result: for item in query_result:
result[item[0]] = item[1] result[item[0]] = item[1]
else: else:
query = """SELECT pair, strftime('%Y-%m', datetime(timestamp, 'unixepoch', '-3 hours')) AS month, query = f"""SELECT pair, strftime('%Y-%m', datetime(timestamp, 'unixepoch', '-3 hours')) AS month,
SUM(amount) AS total_profit SUM(amount) AS total_profit
FROM profits_table FROM profits_table
GROUP BY pair, month;""" GROUP BY pair, month;"""
with db_cursor() as cursor:
cursor.execute(query) cursor.execute(query)
query_result = cursor.fetchall() query_result = cursor.fetchall()
connection.close()
for item in query_result: for item in query_result:
if item[0].replace("/","")==pair: if item[0].replace("/","")==pair:
result[item[1]] = item[2] result[item[1]] = item[2]
@ -296,9 +300,11 @@ def last_n_deals(n):
''' '''
Returns a list of the latest n deals Returns a list of the latest n deals
''' '''
with db_cursor() as cursor: connection = sqlite3.connect(profits_database)
cursor.execute("SELECT * FROM profits_table ORDER BY timestamp DESC LIMIT ?",(n,)) cursor = connection.cursor()
cursor.execute(f"SELECT * FROM profits_table ORDER BY timestamp DESC LIMIT ?",(n,))
result = cursor.fetchall() result = cursor.fetchall()
connection.close()
return result return result
@ -332,34 +338,98 @@ def last_n_lines(file_name,width,amount=4,full_log=False):
return result[:amount],len(file_contents) return result[:amount],len(file_contents)
def tail_log(filename, lines=200): def return_parkinson_backtests(broker, days, max_rank):
if not os.path.exists(filename): '''
return [] Returns a dictionary containing backtests with the format {coin: value}
'''
if broker not in ["binance", "gateio", "kucoin", "okx", "bybit"]:
return {}
block_size = 1024 evaluation_dictionary = {}
blocks = [] start_of_day = int(time.mktime(datetime.datetime.now().date().timetuple()))
with open(filename, 'rb') as f: since = int(start_of_day - 60*60*24*days)
f.seek(0, 2)
#total_bytes = remaining_bytes = f.tell()
remaining_bytes = f.tell()
while len(blocks) < lines and remaining_bytes > 0: # Getting the data from the database
read_bytes = min(block_size, remaining_bytes) print("Querying database...")
f.seek(-read_bytes, 1) conn = sqlite3.connect(f"data/{broker}.db")
block = f.read(read_bytes).splitlines() cursor = conn.cursor()
f.seek(-read_bytes, 1) cursor.execute('SELECT * FROM volatilities_table WHERE timestamp > ?', (since,))
rows = cursor.fetchall()
conn.close()
# Prepend to blocks (since we're reading backwards) # Parse the data
blocks = block[-(len(blocks)+1):] + blocks print("Parsing the data...")
remaining_bytes -= read_bytes for row in rows:
if row[0] not in evaluation_dictionary:
evaluation_dictionary[row[0]] = [row[2]]
else:
evaluation_dictionary[row[0]].append(row[2])
# Decode and filter empty lines #Calculate weighted averages
result = [line.decode('utf-8', errors='ignore').strip() for line in blocks if line.strip()] print("Calculating weighted averages")
return result[-lines:],len(result[-lines:]) weighted_averages = {}
for key in evaluation_dictionary:
multiplier = len(evaluation_dictionary[key])
total = 0
for value in evaluation_dictionary[key][::-1]:
total+=value*multiplier/len(evaluation_dictionary[key])
multiplier-=1
weighted_averages[key] = total/len(evaluation_dictionary[key])
#Filter by rank
print("Filtering results by CMC rank")
coins_accepted = []
market_caps = get_market_caps(max_rank)
for result in market_caps:
coins_accepted.append(result["symbol"])
for coin in weighted_averages.copy():
if coin.split("/")[0] not in coins_accepted:
del(weighted_averages[coin])
#Checking open markets
print("Filtering results by market state")
exchange_class = getattr(ccxt, broker)
broker = exchange_class({
"apiKey": "",
"secret": "",
"timeout": 30000,
"enableRateLimit": True,
'options': {
'newOrderRespType': 'FULL'}
})
markets = broker.load_markets()
for key in weighted_averages.copy():
if key not in markets or not markets[key]["active"]:
del(weighted_averages[key])
return weighted_averages
stats_api = Flask(__name__) stats_api = Flask(__name__)
@stats_api.route("/fetch_backtests")
def fetch_backtests():
'''
GET request
Parameters: 'exchange_name" -> string
'days' -> int
'max_rank' -> int
'''
if "X-API-KEY" in request.headers and request.headers.get("X-API-KEY") in valid_keys:
try:
broker = request.args.get("exchange_name")
days = int(request.args.get("days")) # type: ignore
max_rank = int(request.args.get("max_rank")) # type: ignore
return return_parkinson_backtests(broker,days,max_rank)
except Exception as e:
print(e)
return jsonify({"HORROR": f"{e}"})
return jsonify({'Error': 'API key invalid'}), 401
@stats_api.route("/fetch_profit_report") @stats_api.route("/fetch_profit_report")
def fetch_profit_report(): def fetch_profit_report():
''' '''
@ -368,15 +438,37 @@ def fetch_profit_report():
Returns: JSON object with profit report data Returns: JSON object with profit report data
''' '''
if not "X-API-KEY" in request.headers or not request.headers.get("X-API-KEY") in get_valid_keys(): if "X-API-KEY" in request.headers and request.headers.get("X-API-KEY") in valid_keys:
return jsonify({'Error': 'API key invalid'}), 401
try: try:
return jsonify(profit_report()) return jsonify(profit_report())
except Exception as e: except Exception as e:
print(e) print(e)
return jsonify({"Error": f"{e}"}) return jsonify({"Error": f"{e}"})
return jsonify({'Error': 'API key invalid'}), 401
@stats_api.route("/clear_caches")
def clear_hashes():
global hashes_db
'''
GET request
'''
if "X-API-KEY" in request.headers and request.headers.get("X-API-KEY") in valid_keys:
hashes_db = {"fetch_last_n_deals":0,
"fetch_last_n_deals_without_history":0,
"fetch_full_log":0,
"fetch_log":0,
"daily_totals":0,
"daily_totals_by_pair":0,
"monthly_totals":0,
"monthly_totals_by_pair":0,
"get_averages":0,
"total_profit":0,
"total_profit_by_pair":0}
return jsonify({"Done":0})
return jsonify({'Error': 'API key invalid'}), 401
@stats_api.route("/fetch_last_n_deals") @stats_api.route("/fetch_last_n_deals")
def fetch_last_n_deals(): def fetch_last_n_deals():
@ -384,15 +476,21 @@ def fetch_last_n_deals():
GET request GET request
Parameter: 'amount_of_deals' -> int Parameter: 'amount_of_deals' -> int
''' '''
if not "X-API-KEY" in request.headers or not request.headers.get("X-API-KEY") in get_valid_keys(): if "X-API-KEY" in request.headers and request.headers.get("X-API-KEY") in valid_keys:
return jsonify({'Error': 'API key invalid'}), 401
try: try:
parameter = request.args.get("amount_of_deals") parameter = request.args.get("amount_of_deals")
response_value = last_n_deals(parameter) response_value = last_n_deals(parameter)
if not cache_requests:
return jsonify({"last_deals": response_value}) return jsonify({"last_deals": response_value})
response_hash = hash(str({"last_deals": response_value}))
if hashes_db["fetch_last_n_deals"]!=response_hash:
hashes_db["fetch_last_n_deals"] = response_hash
return jsonify({"last_deals": response_value})
return jsonify({"no_changes": True})
except Exception as e: except Exception as e:
print(e) print(e)
return jsonify({"last_deals":""}) return jsonify({"last_deals":""})
return jsonify({'Error': 'API key invalid'}), 401
@stats_api.route("/fetch_last_n_deals_without_history") @stats_api.route("/fetch_last_n_deals_without_history")
@ -401,16 +499,22 @@ def fetch_last_n_deals_without_history():
GET request GET request
Parameter: 'amount_of_deals' -> int Parameter: 'amount_of_deals' -> int
''' '''
if not "X-API-KEY" in request.headers or not request.headers.get("X-API-KEY") in get_valid_keys(): if "X-API-KEY" in request.headers and request.headers.get("X-API-KEY") in valid_keys:
return jsonify({'Error': 'API key invalid'}), 401
try: try:
parameter = request.args.get("amount_of_deals") parameter = request.args.get("amount_of_deals")
#return jsonify({"last_deals": last_n_deals_without_history(parameter)}) #return jsonify({"last_deals": last_n_deals_without_history(parameter)})
response_value = last_n_deals_without_history(parameter) response_value = last_n_deals_without_history(parameter)
if not cache_requests:
return jsonify({"last_deals": response_value}) return jsonify({"last_deals": response_value})
response_hash = hash(str({"last_deals": response_value}))
if hashes_db["fetch_last_n_deals_without_history"]!=response_hash:
hashes_db["fetch_last_n_deals_without_history"] = response_hash
return jsonify({"last_deals": response_value})
return jsonify({"no_changes": True})
except Exception as e: except Exception as e:
print(e) print(e)
return jsonify({"last_deals":""}) return jsonify({"last_deals":""})
return jsonify({'Error': 'API key invalid'}), 401
@stats_api.route("/fetch_full_log") @stats_api.route("/fetch_full_log")
@ -421,16 +525,22 @@ def fetch_full_log():
It trims the full log to 200 lines, to avoid sending too much data to the client. It trims the full log to 200 lines, to avoid sending too much data to the client.
''' '''
if not "X-API-KEY" in request.headers or not request.headers.get("X-API-KEY") in get_valid_keys(): if "X-API-KEY" in request.headers and request.headers.get("X-API-KEY") in valid_keys:
return jsonify({'Error': 'API key invalid'}), 401
try: try:
exchange_name = request.args.get("exchange_name") exchange_name = request.args.get("exchange_name")
width = 0 width = 0
last_lines, amount_of_lines = tail_log(f"../logs/{exchange_name}.log", 200) last_lines,amount_of_lines = last_n_lines(f"../logs/{exchange_name}.log",width,0,full_log=True)
if not cache_requests:
return jsonify({"line": last_lines[-200:], "amount_of_lines": amount_of_lines}) return jsonify({"line": last_lines[-200:], "amount_of_lines": amount_of_lines})
response_hash = hash(str({"line": last_lines, "amount_of_lines": amount_of_lines}))
if hashes_db["fetch_full_log"]!=response_hash:
hashes_db["fetch_full_log"] = response_hash
return jsonify({"line": last_lines[-200:], "amount_of_lines": amount_of_lines})
return jsonify({"no_changes": True})
except Exception as e: except Exception as e:
print(e) print(e)
return {"line": [""]*width,"amount_of_lines": 0} return {"line": [""]*width,"amount_of_lines": 0}
return jsonify({'Error': 'API key invalid'}), 401
@stats_api.route("/fetch_log") @stats_api.route("/fetch_log")
@ -441,33 +551,45 @@ def fetch_log():
'width' -> int 'width' -> int
'amount' -> int 'amount' -> int
''' '''
if not "X-API-KEY" in request.headers or not request.headers.get("X-API-KEY") in get_valid_keys(): if "X-API-KEY" in request.headers and request.headers.get("X-API-KEY") in valid_keys:
return jsonify({'Error': 'API key invalid'}), 401
try: try:
exchange_name = request.args.get("exchange_name") exchange_name = request.args.get("exchange_name")
width = int(request.args.get("width")) # type: ignore width = int(request.args.get("width")) # type: ignore
amount = int(request.args.get("amount")) # type: ignore amount = int(request.args.get("amount")) # type: ignore
last_lines,total_amount_of_lines = last_n_lines(f"../logs/{exchange_name}.log",width,amount) last_lines,total_amount_of_lines = last_n_lines(f"../logs/{exchange_name}.log",width,amount)
if not cache_requests:
return jsonify({"line": last_lines, "amount_of_lines": total_amount_of_lines}) return jsonify({"line": last_lines, "amount_of_lines": total_amount_of_lines})
response_hash = hash(str({"line": last_lines, "amount_of_lines": total_amount_of_lines}))
if hashes_db["fetch_log"]!=response_hash:
hashes_db["fetch_log"] = response_hash
return jsonify({"line": last_lines, "amount_of_lines": total_amount_of_lines})
return jsonify({"no_changes": True})
except Exception as e: except Exception as e:
print(e) print(e)
return {"line": [""]*10,"amount_of_lines": 0} return {"line": [""]*10,"amount_of_lines": 0}
return jsonify({'Error': 'API key invalid'}), 401
@stats_api.route("/combined_totals") @stats_api.route("/combined_totals")
def combined_totals(): def combined_totals():
if not "X-API-KEY" in request.headers or not request.headers.get("X-API-KEY") in get_valid_keys(): if "X-API-KEY" in request.headers and request.headers.get("X-API-KEY") in valid_keys:
return jsonify({'Error': 'API key invalid'}), 401
daily_totals = daily_and_monthly_totals() daily_totals = daily_and_monthly_totals()
return jsonify({"combined": daily_totals}) return jsonify({"combined": daily_totals})
return jsonify({'Error': 'API key invalid'}), 401
@stats_api.route("/daily_totals") @stats_api.route("/daily_totals")
def get_daily_totals(): def get_daily_totals():
if not "X-API-KEY" in request.headers or not request.headers.get("X-API-KEY") in get_valid_keys(): if "X-API-KEY" in request.headers and request.headers.get("X-API-KEY") in valid_keys:
return jsonify({'Error': 'API key invalid'}), 401
daily_totals = query_daily_totals() daily_totals = query_daily_totals()
if not cache_requests:
return jsonify(daily_totals) return jsonify(daily_totals)
response_hash = hash(str(daily_totals))
if hashes_db["daily_totals"]!=response_hash:
hashes_db["daily_totals"] = response_hash
return jsonify(daily_totals)
return jsonify({"no_changes": True})
return jsonify({'Error': 'API key invalid'}), 401
@stats_api.route("/daily_totals_by_pair") @stats_api.route("/daily_totals_by_pair")
@ -477,24 +599,36 @@ def get_daily_totals_by_pair():
Parameters: 'base' -> string Parameters: 'base' -> string
'quote' -> string 'quote' -> string
''' '''
if not "X-API-KEY" in request.headers or not request.headers.get("X-API-KEY") in get_valid_keys(): if "X-API-KEY" in request.headers and request.headers.get("X-API-KEY") in valid_keys:
return jsonify({'Error': 'API key invalid'}), 401
try: try:
base = request.args.get("base") base = request.args.get("base")
quote = request.args.get("quote") quote = request.args.get("quote")
daily_totals = query_daily_totals(f"{base}{quote}") daily_totals = query_daily_totals(f"{base}{quote}")
if not cache_requests:
return jsonify(daily_totals) return jsonify(daily_totals)
response_hash = hash(str(daily_totals))
if hashes_db["daily_totals_by_pair"]!=response_hash:
hashes_db["daily_totals_by_pair"] = response_hash
return jsonify(daily_totals)
return jsonify({"no_changes": True})
except Exception as e: except Exception as e:
print(e) print(e)
return jsonify({'Error': 'Halp'}) return jsonify({'Error': 'Halp'})
return jsonify({'Error': 'API key invalid'}), 401
@stats_api.route("/monthly_totals") @stats_api.route("/monthly_totals")
def get_monthly_totals(): def get_monthly_totals():
if not "X-API-KEY" in request.headers or not request.headers.get("X-API-KEY") in get_valid_keys(): if "X-API-KEY" in request.headers and request.headers.get("X-API-KEY") in valid_keys:
return jsonify({'Error': 'API key invalid'}), 401
monthly_totals = query_monthly_totals() monthly_totals = query_monthly_totals()
if not cache_requests:
return jsonify(monthly_totals) return jsonify(monthly_totals)
response_hash = hash(str(monthly_totals))
if hashes_db["monthly_totals"]!=response_hash:
hashes_db["monthly_totals"] = response_hash
return jsonify(monthly_totals)
return jsonify({"no_changes": True})
return jsonify({'Error': 'API key invalid'}), 401
@stats_api.route("/monthly_totals_by_pair") @stats_api.route("/monthly_totals_by_pair")
@ -504,47 +638,67 @@ def get_monthly_totals_by_pair():
Parameters: 'base' -> string Parameters: 'base' -> string
'quote' -> string 'quote' -> string
''' '''
if not "X-API-KEY" in request.headers or not request.headers.get("X-API-KEY") in get_valid_keys(): if "X-API-KEY" in request.headers and request.headers.get("X-API-KEY") in valid_keys:
return jsonify({'Error': 'API key invalid'}), 401
try: try:
base = request.args.get("base") base = request.args.get("base")
quote = request.args.get("quote") quote = request.args.get("quote")
monthly_totals = query_monthly_totals(f"{base}{quote}") monthly_totals = query_monthly_totals(f"{base}{quote}")
if not cache_requests:
return jsonify(monthly_totals) return jsonify(monthly_totals)
response_hash = hash(str(monthly_totals))
if hashes_db["monthly_totals_by_pair"]!=response_hash:
hashes_db["monthly_totals_by_pair"] = response_hash
return jsonify(monthly_totals)
return jsonify({"no_changes": True})
except Exception as e: except Exception as e:
print(e) print(e)
return jsonify({'Error': 'Halp'}) return jsonify({'Error': 'Halp'})
return jsonify({'Error': 'API key invalid'}), 401
@stats_api.route("/get_averages") @stats_api.route("/get_averages")
def get_averages(): def get_averages():
if not "X-API-KEY" in request.headers or not request.headers.get("X-API-KEY") in get_valid_keys(): if "X-API-KEY" in request.headers and request.headers.get("X-API-KEY") in valid_keys:
return jsonify({'Error': 'API key invalid'}), 401
try: try:
daily_totals = query_daily_totals() daily_totals = query_daily_totals()
val_30 = 0 val_30 = 0
val_7 = 0 val_7 = 0
recent_days = sorted(daily_totals.keys(), reverse=True)[:30] acc_30 = []
acc_30 = [daily_totals[date] for date in recent_days[:30]] acc_7 = []
acc_7 = [daily_totals[date] for date in recent_days[:7]] for x in sorted(daily_totals):
acc_30.append(daily_totals[x])
acc_7.append(daily_totals[x])
length_30 = min(30,len(acc_30)) #Last 30 days length_30 = min(30,len(acc_30)) #Last 30 days
length_7 = min(7,len(acc_7)) #Last 7 days length_7 = min(7,len(acc_7)) #Last 7 days
for _ in range(length_30): for _ in range(length_30):
val_30 += acc_30.pop() val_30 += acc_30.pop()
for _ in range(length_7): for _ in range(length_7):
val_7 += acc_7.pop() val_7 += acc_7.pop()
if not cache_requests:
return jsonify({"30_day": val_30/length_30, "7_day": val_7/length_7}) return jsonify({"30_day": val_30/length_30, "7_day": val_7/length_7})
response_hash = hash(str({"30_day": val_30/length_30, "7_day": val_7/length_7}))
if hashes_db["get_averages"]!=response_hash:
hashes_db["get_averages"] = response_hash
return jsonify({"30_day": val_30/length_30, "7_day": val_7/length_7})
return jsonify({"no_changes": True})
except Exception as e: except Exception as e:
print(e) print(e)
return jsonify({'Error': 'Halp'}) return jsonify({'Error': 'Halp'})
return jsonify({'Error': 'API key invalid'}), 401
@stats_api.route("/total_profit") @stats_api.route("/total_profit")
def total_profit(): def total_profit():
if not "X-API-KEY" in request.headers or not request.headers.get("X-API-KEY") in get_valid_keys(): if "X-API-KEY" in request.headers and request.headers.get("X-API-KEY") in valid_keys:
return jsonify({'Error': 'API key invalid'}), 401
total = query_total_profit() total = query_total_profit()
if not cache_requests:
return jsonify({"Total profit": total}) return jsonify({"Total profit": total})
response_hash = hash(str({"Total profit": total}))
if hashes_db["total_profit"]!=response_hash:
hashes_db["total_profit"] = response_hash
return jsonify({"Total profit": total})
return jsonify({"no_changes": True})
return jsonify({'Error': 'API key invalid'}), 401
@stats_api.route("/total_profit_by_pair") @stats_api.route("/total_profit_by_pair")
@ -554,25 +708,33 @@ def total_profit_by_pair():
Parameters: 'base' -> string Parameters: 'base' -> string
'quote' -> string 'quote' -> string
''' '''
if not "X-API-KEY" in request.headers or not request.headers.get("X-API-KEY") in get_valid_keys(): if "X-API-KEY" in request.headers and request.headers.get("X-API-KEY") in valid_keys:
return jsonify({'Error': 'API key invalid'}), 401
try: try:
base = request.args.get("base") base = request.args.get("base")
quote = request.args.get("quote") quote = request.args.get("quote")
total = query_total_profit(f"{base}{quote}") total = query_total_profit(f"{base}{quote}")
if not cache_requests:
return jsonify({"Total profit": total}) return jsonify({"Total profit": total})
response_hash = hash(str({"Total profit": total}))
if hashes_db["total_profit_by_pair"]!=response_hash:
hashes_db["total_profit_by_pair"] = response_hash
return jsonify({"Total profit": total})
return jsonify({"no_changes": True})
except Exception as e: except Exception as e:
print(e) print(e)
return jsonify({'Error': 'Halp'}) return jsonify({'Error': 'Halp'})
return jsonify({'Error': 'API key invalid'}), 401
if __name__=="__main__": if __name__=="__main__":
# Load valid keys from database
valid_keys = load_keys_from_db("api_credentials.db")
#Waitress #Waitress
logger = logging.getLogger('waitress') logger = logging.getLogger('waitress')
logger.setLevel(logging.INFO) logger.setLevel(logging.INFO)
serve(stats_api,host="0.0.0.0",port=5010) serve(stats_api,host="0.0.0.0",port=5010, threads=32)
#Flask #Flask
# app.run(host="0.0.0.0", port=5010, debug=True) # app.run(host="0.0.0.0", port=5010, debug=True)