small optimizations

This commit is contained in:
Nicolás Sánchez 2025-08-17 10:41:16 -03:00
parent 3353a09db1
commit 9855c64d81
1 changed files with 40 additions and 37 deletions

55
main.py
View File

@ -267,12 +267,15 @@ def restart_pair_no_json(base: str, quote: str) -> int:
return 1 return 1
def main_loop(): def main_routine():
global last_market_reload global last_market_reload
global reload_interval global reload_interval
global screen_buffer global screen_buffer
executor = ThreadPoolExecutor(max_workers=MAX_WORKERS) executor = ThreadPoolExecutor(max_workers=MAX_WORKERS)
is_testnet = "TESTNET " if broker.get_config()["is_sandbox"] else ""
exchange_version_label = f"{bright_white}{broker.get_config()['exchange'].upper()} {is_testnet}{white}| DCAv2 {version} | CCXT v{ccxt.__version__}"
separator_line = blue + "="*80 + white
while True: while True:
#Restart traders that have the restart flag raised and remove traders that have the quit flag raised #Restart traders that have the restart flag raised and remove traders that have the quit flag raised
@ -323,42 +326,41 @@ def main_loop():
curr = 0 curr = 0
top = 0 top = 0
long_traders_status_strings = []
short_traders_status_strings = []
paused_traders_status_strings = []
global_status["paused_traders"].clear()
for instance in running_traders: for instance in running_traders:
if not instance.config.get_is_short(): if not instance.config.get_is_short():
curr += int(instance.get_status_dict()["so_amount"]) # For the safety order occupancy percentage calculation curr += int(instance.get_status_dict()["so_amount"]) # For the safety order occupancy percentage calculation
top += int(instance.config.get_no_of_safety_orders()) # It shows the percentage of safety orders not filled top += int(instance.config.get_no_of_safety_orders()) # It shows the percentage of safety orders not filled
if not instance.quit: #Why? Maybe to protect return_status() from weird errors if the trader errored out? if "status_string" in instance.get_status_dict(): # status_strings
long_traders_status_strings.append(str(instance))
elif "status_string" in instance.get_status_dict():
short_traders_status_strings.append(str(instance))
try: try:
if instance.config.get_pair() in price_list and price_list[instance.config.get_pair()] is not None: if instance.config.get_pair() in price_list and price_list[instance.config.get_pair()] is not None:
instance.get_status_dict()["price"] = price_list[instance.config.get_pair()] instance.get_status_dict()["price"] = price_list[instance.config.get_pair()]
except Exception as e: except Exception as e:
broker.logger.log_this(f"Exception while querying for pair price, key not present on price_list dictionary: {e}",1,instance.config.get_pair()) broker.logger.log_this(f"Exception while querying for pair price, key not present on price_list dictionary: {e}",1,instance.config.get_pair())
#Clear the screen buffer #Add paused traders to the paused trader list
screen_buffer.clear() if instance.pause:
global_status["paused_traders"].append(instance.config.get_pair())
paused_traders_status_strings.append(f"{cyan}Paused pairs: {list(global_status['paused_traders'])}{white}")
#Append worker data to screen buffer, shorts first. #Append worker data to screen buffer, shorts first.
for instance in running_traders: screen_buffer.extend(short_traders_status_strings + long_traders_status_strings)
if instance.config.get_is_short() and "status_string" in instance.get_status_dict():
screen_buffer.append(str(instance)) #Appends paused pairs to the screen buffer
for instance in running_traders: if paused_traders_status_strings!=[]:
if not instance.config.get_is_short() and "status_string" in instance.get_status_dict(): screen_buffer.extend(paused_traders_status_strings)
screen_buffer.append(str(instance))
#Updates some global status variables prior to deletion of those #Updates some global status variables prior to deletion of those
if len(running_traders)!=len(global_status["online_workers"]): if len(running_traders)!=len(global_status["online_workers"]):
global_status["online_workers"] = [instance.config.get_pair() for instance in running_traders] global_status["online_workers"] = [instance.config.get_pair() for instance in running_traders]
#Check for paused pairs
global_status["paused_traders"] = [instance.config.get_pair() for instance in running_traders if instance.pause]
if global_status["paused_traders"]:
screen_buffer.append(f"{cyan}Paused pairs: {list(global_status['paused_traders'])}{white}")
#Check for paused pairs
for instance in running_traders:
if instance.pause:
screen_buffer.append(f"{instance.config.get_pair()} paused: {instance.get_status_dict()['pause_reason']}")
#Prints general info #Prints general info
instance_uptime = int(time.time()) - instance_start_time instance_uptime = int(time.time()) - instance_start_time
screen_buffer.append(time.strftime(f"[%Y/%m/%d %H:%M:%S] | {len(running_traders)} traders online | Instance uptime: {seconds_to_time(instance_uptime)}")) screen_buffer.append(time.strftime(f"[%Y/%m/%d %H:%M:%S] | {len(running_traders)} traders online | Instance uptime: {seconds_to_time(instance_uptime)}"))
@ -373,14 +375,16 @@ def main_loop():
color = yellow color = yellow
if so_index<35: if so_index<35:
color = green color = green
is_testnet = "TESTNET " if broker.get_config()["is_sandbox"] else "" screen_buffer.append(f"{exchange_version_label} | Safety order occupancy: {color}{so_index}%{white}")
screen_buffer.append(f"{bright_white}{broker.get_config()['exchange'].upper()} {is_testnet}{white}| DCAv2 {version} | CCXT v{ccxt.__version__} | Safety order occupancy: {color}{so_index}%{white}") screen_buffer.append(separator_line)
screen_buffer.append(blue + "="*80 + white)
#Print screen buffer #Print screen buffer
for line in screen_buffer: for line in screen_buffer:
print(line) print(line)
#Clear the screen buffer
screen_buffer.clear()
#Updates global status and remove keys that should not be public #Updates global status and remove keys that should not be public
global_status["instance_uptime"] = instance_uptime global_status["instance_uptime"] = instance_uptime
global_status["config"] = broker.get_config() global_status["config"] = broker.get_config()
@ -1346,7 +1350,7 @@ def reload_trader_config():
def run_API(): def run_API():
serve(base_api, host="0.0.0.0", port=broker.get_config()["port"], threads=16) serve(base_api, host="0.0.0.0", port=broker.get_config()["port"])
#base_api.run(host="0.0.0.0", port=broker.get_config()["port"]) #base_api.run(host="0.0.0.0", port=broker.get_config()["port"])
@ -2491,8 +2495,7 @@ if __name__=="__main__":
api_thread.start() api_thread.start()
try: try:
while True: main_routine()
main_loop()
except KeyboardInterrupt: except KeyboardInterrupt:
api_thread.join() api_thread.join()
shutdown_handler(signal.SIGINT, None) shutdown_handler(signal.SIGINT, None)