symbol renaming

This commit is contained in:
Nicolás Sánchez 2025-06-09 21:35:57 -03:00
parent 846411f550
commit edce99c431
1 changed files with 182 additions and 182 deletions

364
main.py
View File

@ -92,7 +92,7 @@ def import_instance(base: str, quote: str, forced_tp_id = None, forced_so_id = N
def add_instance(base: str, quote: str) -> int: def add_instance(base: str, quote: str) -> int:
''' '''
Adds a new instance of the trader class to the running_instances list. Adds a new instance of the trader class to the running_traders list.
Parameters: Parameters:
base (str): The base currency of the pair. base (str): The base currency of the pair.
@ -104,9 +104,9 @@ def add_instance(base: str, quote: str) -> int:
#Check if the pair is already running #Check if the pair is already running
pair = f"{base}{quote}" pair = f"{base}{quote}"
for x in running_instances: for instance in running_traders:
if f"{x.base}{x.quote}"==pair: if f"{instance.base}{instance.quote}"==pair:
broker.logger.log_this(f"Pair already running, duplicate instances are not allowed",1,pair) broker.logger.log_this(f"Pair already running, duplicate traders are not allowed",1,pair)
return 1 return 1
#Initialize the trader object and add the pair to the tickers list #Initialize the trader object and add the pair to the tickers list
@ -128,7 +128,7 @@ def initialize_instance(base: str, quote: str) -> int:
int: 0 if successful int: 0 if successful
''' '''
broker.logger.log_this(f"Initializing {f'{base}/{quote}'}") broker.logger.log_this(f"Initializing {f'{base}/{quote}'}")
running_instances.append(trader.trader(broker,f'{base}/{quote}')) running_traders.append(trader.trader(broker,f'{base}/{quote}'))
if f'{base}{quote}' not in tickers: if f'{base}{quote}' not in tickers:
tickers.append(f'{base}{quote}') tickers.append(f'{base}{quote}')
return 0 return 0
@ -231,23 +231,23 @@ def restart_pair_no_json(base: str, quote: str) -> int:
try: try:
order_list = broker.fetch_full_orders(tickers) order_list = broker.fetch_full_orders(tickers)
for x in running_instances: for instance in running_traders:
if f"{base}/{quote}"==x.config.get_pair(): if f"{base}/{quote}"==instance.config.get_pair():
x.pause = True instance.pause = True
#Backing up old status file #Backing up old status file
x.status.save_to_file(is_backup=True) instance.status.save_to_file(is_backup=True)
#Here, we could open a duster (if needed) #Here, we could open a duster (if needed)
for order in order_list: for order in order_list:
if order["symbol"]==f"{base}/{quote}" and x.config.get_is_short() and order["side"]=="sell": if order["symbol"]==f"{base}/{quote}" and instance.config.get_is_short() and order["side"]=="sell":
broker.logger.log_this(f"Cancelling old sell orders",2,f"{base}/{quote}") broker.logger.log_this(f"Cancelling old sell orders",2,f"{base}/{quote}")
broker.cancel_order(order["id"],order["symbol"]) broker.cancel_order(order["id"],order["symbol"])
elif order["symbol"]==f"{base}/{quote}" and not x.config.get_is_short() and order["side"]=="buy": elif order["symbol"]==f"{base}/{quote}" and not instance.config.get_is_short() and order["side"]=="buy":
broker.logger.log_this(f"Cancelling old buy orders",2,f"{base}/{quote}") broker.logger.log_this(f"Cancelling old buy orders",2,f"{base}/{quote}")
broker.cancel_order(order["id"],order["symbol"]) broker.cancel_order(order["id"],order["symbol"])
try: try:
running_instances.remove(x) running_traders.remove(instance)
except ValueError: except ValueError:
broker.logger.log_this(f"Instance {x.config.get_pair()} not found in running_instances.",1,x.config.get_pair()) broker.logger.log_this(f"Instance {instance.config.get_pair()} not found in running_traders.",1,instance.config.get_pair())
add_instance(base,quote) add_instance(base,quote)
return 0 return 0
return 1 return 1
@ -263,39 +263,39 @@ def main_loop():
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
for x in running_instances: for instance in running_traders:
if x.restart and x.config.get_attempt_restart(): if instance.restart and instance.config.get_attempt_restart():
broker.logger.log_this(f"Restarting trader",1,x.config.get_pair()) broker.logger.log_this(f"Restarting trader",1,instance.config.get_pair())
restart_pair_no_json(x.base,x.quote) restart_pair_no_json(instance.base,instance.quote)
if x.quit: if instance.quit:
#Here, check if a duster is needed #Here, check if a duster is needed
broker.logger.log_this(f"Quit flag raised, removing pair.",0,x.config.get_pair()) broker.logger.log_this(f"Quit flag raised, removing pair.",0,instance.config.get_pair())
broker.logger.log_this(f"Quit flag raised, removing pair: {x.config.get_pair()}",-1) #Forced message to TG broker.logger.log_this(f"Quit flag raised, removing pair: {instance.config.get_pair()}",-1) #Forced message to TG
if f"{x.base}{x.quote}" in tickers: if f"{instance.base}{instance.quote}" in tickers:
tickers.remove(f"{x.base}{x.quote}") tickers.remove(f"{instance.base}{instance.quote}")
broker.remove_pair_from_config(f"{x.base}{x.quote}") broker.remove_pair_from_config(f"{instance.base}{instance.quote}")
broker.rewrite_config_file() broker.rewrite_config_file()
if x.config.get_pair() in worker_status: if instance.config.get_pair() in worker_status:
del(worker_status[x.config.get_pair()]) del(worker_status[instance.config.get_pair()])
try: try:
running_instances.remove(x) running_traders.remove(instance)
except ValueError: except ValueError:
broker.logger.log_this(f"Instance {x.config.get_pair()} not found in running_instances.",1,x.config.get_pair()) broker.logger.log_this(f"Instance {instance.config.get_pair()} not found in running_traders.",1,instance.config.get_pair())
#Adds pending traders #Adds pending traders
if bool(instances_to_add): if bool(instances_to_add):
for x in instances_to_add: for instance in instances_to_add:
running_instances.append(x) running_traders.append(instance)
instances_to_add.clear() instances_to_add.clear()
#Prepares the trader threads #Prepares the trader threads
open_orders = broker.fetch_open_orders(tickers) open_orders = broker.fetch_open_orders(tickers)
pairs_to_fetch = [] pairs_to_fetch = []
online_pairs = [] online_pairs = []
for x in running_instances: for instance in running_traders:
threads.append(Thread(target=x.check_status,args=(open_orders,))) threads.append(Thread(target=instance.check_status,args=(open_orders,)))
online_pairs.append(f"{x.base}{x.quote}") online_pairs.append(f"{instance.base}{instance.quote}")
pairs_to_fetch.append(x.config.get_pair()) pairs_to_fetch.append(instance.config.get_pair())
#Here, append the dusters' pairs to pairs_to_fetch, if missing. #Here, append the dusters' pairs to pairs_to_fetch, if missing.
# #
@ -326,45 +326,45 @@ def main_loop():
curr = 0 curr = 0
top = 0 top = 0
for x in running_instances: for instance in running_traders:
if not x.config.get_is_short(): if not instance.config.get_is_short():
curr += int(x.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(x.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 x.quit: #Why? Maybe to protect return_status() from weird errors if the trader errored out? if not instance.quit: #Why? Maybe to protect return_status() from weird errors if the trader errored out?
try: try:
if x.config.get_pair() in price_list and price_list[x.config.get_pair()] is not None: if instance.config.get_pair() in price_list and price_list[instance.config.get_pair()] is not None:
x.get_status_dict()["price"] = price_list[x.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,x.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())
worker_status[x.config.get_pair()] = x.get_status_dict() worker_status[instance.config.get_pair()] = instance.get_status_dict()
#Clear the screen buffer #Clear the screen buffer
screen_buffer.clear() screen_buffer.clear()
#Append worker data to screen buffer, shorts first. #Append worker data to screen buffer, shorts first.
for x in running_instances: for instance in running_traders:
if x.config.get_is_short() and "status_string" in x.get_status_dict(): if instance.config.get_is_short() and "status_string" in instance.get_status_dict():
screen_buffer.append(str(x)) screen_buffer.append(str(instance))
for x in running_instances: for instance in running_traders:
if not x.config.get_is_short() and "status_string" in x.get_status_dict(): if not instance.config.get_is_short() and "status_string" in instance.get_status_dict():
screen_buffer.append(str(x)) 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
global_status["online_workers"] = online_pairs.copy() global_status["online_workers"] = online_pairs.copy()
#Check for paused pairs #Check for paused pairs
global_status["paused_traders"] = [x.config.get_pair() for x in running_instances if x.pause] global_status["paused_traders"] = [instance.config.get_pair() for instance in running_traders if instance.pause]
if global_status["paused_traders"]: if global_status["paused_traders"]:
screen_buffer.append(f"{cyan}Paused pairs: {list(global_status['paused_traders'])}{white}") screen_buffer.append(f"{cyan}Paused pairs: {list(global_status['paused_traders'])}{white}")
#Check for paused pairs #Check for paused pairs
for x in running_instances: for instance in running_traders:
if x.pause: if instance.pause:
screen_buffer.append(f"{x.config.get_pair()} paused: {x.get_status_dict()['pause_reason']}") 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_instances)} 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)}"))
if top==0: #To protect from division by zero when there are no traders active if top==0: #To protect from division by zero when there are no traders active
so_index=100 so_index=100
@ -393,7 +393,7 @@ def main_loop():
#Toggle pauses #Toggle pauses
if toggle_pauses: if toggle_pauses:
for instance in running_instances: for instance in running_traders:
if instance.config.get_pair() in toggle_pauses: if instance.config.get_pair() in toggle_pauses:
instance.pause = not instance.pause instance.pause = not instance.pause
toggle_pauses.clear() toggle_pauses.clear()
@ -1365,8 +1365,8 @@ def unwrapped_add_pair(base,quote):
try: try:
#Check if the trader is already running #Check if the trader is already running
for x in running_instances: for instance in running_traders:
if f"{base}/{quote}"==x.config.get_pair(): if f"{base}/{quote}"==instance.config.get_pair():
broker.logger.log_this(f"Pair already running",1,f"{base}/{quote}") broker.logger.log_this(f"Pair already running",1,f"{base}/{quote}")
return jsonify({"Error": "Pair already running"}) return jsonify({"Error": "Pair already running"})
@ -1416,9 +1416,9 @@ def unwrapped_remove_pair(base,quote):
''' '''
try: try:
for x in running_instances: for instance in running_traders:
if f"{base}/{quote}"==x.config.get_pair(): if f"{base}/{quote}"==instance.config.get_pair():
x.quit = True instance.quit = True
return jsonify({"Success": "Pair to be removed"}) return jsonify({"Success": "Pair to be removed"})
except Exception as e: except Exception as e:
broker.logger.log_this(f"Exception while removing instance: {e}",1,f"{base}/{quote}") broker.logger.log_this(f"Exception while removing instance: {e}",1,f"{base}/{quote}")
@ -1484,13 +1484,13 @@ def unwrapped_switch_to_long(base,quote,calculate_profits):
#Close trader and orders and pull info our of the orders #Close trader and orders and pull info our of the orders
if f"{base}{quote}" not in broker.get_pairs(): if f"{base}{quote}" not in broker.get_pairs():
return jsonify({"Error": "Pair not running"}) return jsonify({"Error": "Pair not running"})
for x in running_instances: for instance in running_traders:
if f"{base}/{quote}"==x.config.get_pair(): if f"{base}/{quote}"==instance.config.get_pair():
x.pause = True instance.pause = True
if x.switch_to_long(ignore_old_long=ignore_old_long)==1: if instance.switch_to_long(ignore_old_long=ignore_old_long)==1:
return jsonify({"Error": "Error in switch_to_long()"}) return jsonify({"Error": "Error in switch_to_long()"})
if x.start_trader()==1: if instance.start_trader()==1:
x.quit = True instance.quit = True
return jsonify({"Error": "Error switching to long mode (wAPI)"}) return jsonify({"Error": "Error switching to long mode (wAPI)"})
return jsonify({"Success": "Pair switched to long mode"}) return jsonify({"Success": "Pair switched to long mode"})
return jsonify({"Error": "Pair not found"}) return jsonify({"Error": "Pair not found"})
@ -1511,25 +1511,25 @@ def unwrapped_switch_to_short(base,quote):
#Close trader and orders and pull info our of the orders #Close trader and orders and pull info our of the orders
if f"{base}{quote}" not in broker.get_pairs(): if f"{base}{quote}" not in broker.get_pairs():
return jsonify({"Error": "Pair not running"}) return jsonify({"Error": "Pair not running"})
for x in running_instances: for instance in running_traders:
if f"{base}/{quote}"==x.config.get_pair() and x.switch_to_short()==1: if f"{base}/{quote}"==instance.config.get_pair() and instance.switch_to_short()==1:
return jsonify({"Error": "Error in switch_to_short()"}) return jsonify({"Error": "Error in switch_to_short()"})
#Restart instance #Restart instance
try: try:
broker.logger.log_this(f"Reinitializing trader",2,f"{base}/{quote}") broker.logger.log_this(f"Reinitializing trader",2,f"{base}/{quote}")
for x in running_instances: for instance in running_traders:
if f"{base}/{quote}"==x.config.get_pair(): if f"{base}/{quote}"==instance.config.get_pair():
x.status.set_take_profit_order(x.broker.empty_order) instance.status.set_take_profit_order(instance.broker.empty_order)
x.so = x.broker.empty_order instance.so = instance.broker.empty_order
#Reloading config file #Reloading config file
x.config.load_from_file() instance.config.load_from_file()
#Enabling autoswitch #Enabling autoswitch
x.config.set_autoswitch(True) instance.config.set_autoswitch(True)
if x.start_trader()==1: if instance.start_trader()==1:
x.quit = True instance.quit = True
return jsonify({"Error": "Error switching to short mode (wAPI)"}) return jsonify({"Error": "Error switching to short mode (wAPI)"})
return jsonify({"Success": "Pair switched to short mode"}) return jsonify({"Success": "Pair switched to short mode"})
except Exception as e: except Exception as e:
@ -1566,10 +1566,10 @@ def unwrapped_load_old_long(base,quote):
#Maybe here we could also check that the keys have the proper values #Maybe here we could also check that the keys have the proper values
#Creates (or modifies) a key in the status dictionary and assigns the contents of the file to that same key. #Creates (or modifies) a key in the status dictionary and assigns the contents of the file to that same key.
for x in running_instances: for instance in running_traders:
if x.config.get_pair()==f"{base}/{quote}": if instance.config.get_pair()==f"{base}/{quote}":
x.get_status_dict()["old_long"]=old_long instance.get_status_dict()["old_long"]=old_long
x.update_status(True) instance.update_status(True)
return jsonify({"Success": "old_long file loaded to status_dict"}) return jsonify({"Success": "old_long file loaded to status_dict"})
return jsonify({"Error": "Pair not found"}) return jsonify({"Error": "Pair not found"})
@ -1592,10 +1592,10 @@ def unwrapped_view_old_long(base,quote,from_file):
with open(f"{base}{quote}.oldlong") as ol: with open(f"{base}{quote}.oldlong") as ol:
old_long = json.load(ol) old_long = json.load(ol)
return jsonify(old_long) return jsonify(old_long)
for x in running_instances: for instance in running_traders:
if f"{base}/{quote}"==x.config.get_pair(): if f"{base}/{quote}"==instance.config.get_pair():
if "old_long" in x.get_status_dict(): if "old_long" in instance.get_status_dict():
return jsonify(x.get_status_dict()["old_long"]) return jsonify(instance.get_status_dict()["old_long"])
return jsonify({"Error": "No old_long info found"}) return jsonify({"Error": "No old_long info found"})
return jsonify({"Error": "Pair not found"}) return jsonify({"Error": "Pair not found"})
except Exception as e: except Exception as e:
@ -1617,13 +1617,13 @@ def unwrapped_switch_to_long_price(base,quote):
''' '''
try: try:
for x in running_instances: for instance in running_traders:
if f"{base}/{quote}"==x.config.get_pair(): if f"{base}/{quote}"==instance.config.get_pair():
if "old_long" in x.get_status_dict(): if "old_long" in instance.get_status_dict():
#minimum_switch_price = (old_target - quote_already_in)/base_left #minimum_switch_price = (old_target - quote_already_in)/base_left
old_target = x.get_status_dict()["old_long"]["tp_price"]*x.get_status_dict()["old_long"]["tp_amount"] old_target = instance.get_status_dict()["old_long"]["tp_price"]*instance.get_status_dict()["old_long"]["tp_amount"]
base_left = x.get_status_dict()["old_long"]["tp_amount"]-x.get_status_dict()["base_bought"] base_left = instance.get_status_dict()["old_long"]["tp_amount"]-instance.get_status_dict()["base_bought"]
minimum_switch_price = (old_target - x.get_status_dict()["quote_spent"])/base_left minimum_switch_price = (old_target - instance.get_status_dict()["quote_spent"])/base_left
return jsonify({"switch_price": minimum_switch_price}) return jsonify({"switch_price": minimum_switch_price})
return jsonify({"Error": "No old_long info found"}) return jsonify({"Error": "No old_long info found"})
return jsonify({"Error": "Pair not found"}) return jsonify({"Error": "Pair not found"})
@ -1647,16 +1647,16 @@ def unwrapped_add_safety_orders(base,quote,amount):
''' '''
try: try:
for x in running_instances: for instance in running_traders:
if f"{base}/{quote}"==x.config.get_pair(): if f"{base}/{quote}"==instance.config.get_pair():
x.pause = True instance.pause = True
#x.no_of_safety_orders += int(amount) #x.no_of_safety_orders += int(amount)
x.config.set_no_of_safety_orders(x.config.get_no_of_safety_orders()+int(amount)) instance.config.set_no_of_safety_orders(instance.config.get_no_of_safety_orders()+int(amount))
broker.logger.log_this("Recalculating safety price table...",1,f"{base}/{quote}") broker.logger.log_this("Recalculating safety price table...",1,f"{base}/{quote}")
x.status.set_safety_price_table(x.calculate_safety_prices(x.status.get_start_price(),x.config.get_no_of_safety_orders(),x.config.get_safety_order_deviance())) instance.status.set_safety_price_table(instance.calculate_safety_prices(instance.status.get_start_price(),instance.config.get_no_of_safety_orders(),instance.config.get_safety_order_deviance()))
broker.logger.log_this(f"Done. Added {amount} safety orders",1,f"{base}/{quote}") broker.logger.log_this(f"Done. Added {amount} safety orders",1,f"{base}/{quote}")
x.update_status(True) instance.update_status(True)
x.pause = False instance.pause = False
return jsonify({"Success": f"Done. Added {amount} safety orders"}) return jsonify({"Success": f"Done. Added {amount} safety orders"})
return jsonify({"Error": "Pair not found"}) return jsonify({"Error": "Pair not found"})
except Exception as e: except Exception as e:
@ -1677,12 +1677,12 @@ def unwrapped_base_add_so_calculation(base,quote):
''' '''
try: try:
for x in running_instances: for instance in running_traders:
if f"{base}/{quote}"==x.config.get_pair(): if f"{base}/{quote}"==instance.config.get_pair():
free_base = x.fetch_free_base() free_base = instance.fetch_free_base()
if free_base is None: if free_base is None:
return jsonify({"Error": "Can't fetch amount of free base on the exchange"}) return jsonify({"Error": "Can't fetch amount of free base on the exchange"})
amount_of_orders = x.base_add_calculation(free_base) amount_of_orders = instance.base_add_calculation(free_base)
return jsonify({"Amount": amount_of_orders, "Free base on exchange": free_base}) return jsonify({"Amount": amount_of_orders, "Free base on exchange": free_base})
return jsonify({"Error": "Can't find the pair in the running instances"}) return jsonify({"Error": "Can't find the pair in the running instances"})
except Exception as e: except Exception as e:
@ -1704,9 +1704,9 @@ def unwrapped_mod_tp_level(base,quote,amount):
''' '''
try: try:
for x in running_instances: for instance in running_traders:
if f"{base}/{quote}"==x.config.get_pair(): if f"{base}/{quote}"==instance.config.get_pair():
x.config.set_tp_level(float(amount)) instance.config.set_tp_level(float(amount))
broker.logger.log_this("Done. The change will take effect when the next take profit order is placed",2,f"{base}/{quote}") broker.logger.log_this("Done. The change will take effect when the next take profit order is placed",2,f"{base}/{quote}")
return jsonify({"Success": "Success. The change will take effect when the next TP order is placed"}) return jsonify({"Success": "Success. The change will take effect when the next TP order is placed"})
except Exception: except Exception:
@ -1725,9 +1725,9 @@ def unwrapped_mod_global_tp_level(amount):
jsonify: A jsonified dictionary detailing the outcome of the operation jsonify: A jsonified dictionary detailing the outcome of the operation
''' '''
for x in running_instances: for instance in running_traders:
try: try:
x.config.set_tp_level(float(amount)) instance.config.set_tp_level(float(amount))
broker.logger.log_this("Done. The change will take effect when the next take profit order is placed",2) broker.logger.log_this("Done. The change will take effect when the next take profit order is placed",2)
except Exception: except Exception:
broker.logger.log_this("Error changing percentage. Ignoring.",2) broker.logger.log_this("Error changing percentage. Ignoring.",2)
@ -1748,13 +1748,13 @@ def unwrapped_last_call(base,quote):
try: try:
if f"{base}{quote}" in broker.get_pairs(): if f"{base}{quote}" in broker.get_pairs():
for x in running_instances: for instance in running_traders:
if f"{base}/{quote}"==x.config.get_pair(): if f"{base}/{quote}"==instance.config.get_pair():
x.status.set_stop_when_profit(not x.status.get_stop_when_profit()) instance.status.set_stop_when_profit(not instance.status.get_stop_when_profit())
x.update_status(True) instance.update_status(True)
if x.status.get_stop_when_profit(): if instance.status.get_stop_when_profit():
x.config.set_autoswitch(False) instance.config.set_autoswitch(False)
x.update_status(True) instance.update_status(True)
return jsonify({"Success": "Trader scheduled to go offline when profit is reached"}) return jsonify({"Success": "Trader scheduled to go offline when profit is reached"})
return jsonify({"Success": "Last call cancelled"}) return jsonify({"Success": "Last call cancelled"})
return jsonify({"Error": "Trader does not exist"}) return jsonify({"Error": "Trader does not exist"})
@ -1782,12 +1782,12 @@ def unwrapped_deferred_last_call(base,quote,yyyymmdd):
limit = time_to_unix(year,month,day) limit = time_to_unix(year,month,day)
if limit==0: if limit==0:
return jsonify({"Error": "Can't convert date to unix"}) return jsonify({"Error": "Can't convert date to unix"})
for x in running_instances: for instance in running_traders:
if f"{base}{quote}"==x.config.get_pair(): if f"{base}{quote}"==instance.config.get_pair():
x.config.set_programmed_stop_time(limit) instance.config.set_programmed_stop_time(limit)
x.config.set_programmed_stop(True) instance.config.set_programmed_stop(True)
#save config file to disk #save config file to disk
x.broker.rewrite_config_file() instance.broker.rewrite_config_file()
return jsonify({"Success": f"Trader scheduled to go offline when profit is reached after {limit}"}) return jsonify({"Success": f"Trader scheduled to go offline when profit is reached after {limit}"})
except Exception: except Exception:
return jsonify({"Error": "Halp"}) return jsonify({"Error": "Halp"})
@ -1808,7 +1808,7 @@ def unwrapped_toggle_pause(base,quote):
try: try:
toggle_pauses.append(f"{base}/{quote}") toggle_pauses.append(f"{base}/{quote}")
for instance in running_instances: for instance in running_traders:
if instance.config.get_pair()==f"{base}/{quote}": if instance.config.get_pair()==f"{base}/{quote}":
if instance.pause: if instance.pause:
instance.status.set_pause_reason("") instance.status.set_pause_reason("")
@ -1830,10 +1830,10 @@ def unwrapped_global_last_call():
try: try:
if broker.get_pairs!=[]: if broker.get_pairs!=[]:
#broker.clear_pairs() #broker.clear_pairs()
for x in running_instances: for instance in running_traders:
x.status.set_stop_when_profit(True) instance.status.set_stop_when_profit(True)
x.config.set_autoswitch(False) instance.config.set_autoswitch(False)
broker.logger.log_this("Modified flag",2,f"{x.base}/{x.quote}") broker.logger.log_this("Modified flag",2,f"{instance.base}/{instance.quote}")
return jsonify({"Success": "All traders scheduled to go offline when profit is reached"}) return jsonify({"Success": "All traders scheduled to go offline when profit is reached"})
return jsonify({"Error": "No traders running"}) return jsonify({"Error": "No traders running"})
except Exception: except Exception:
@ -1850,9 +1850,9 @@ def unwrapped_cancel_global_last_call():
try: try:
if broker.get_pairs!=[]: if broker.get_pairs!=[]:
#broker.clear_pairs() #broker.clear_pairs()
for x in running_instances: for instance in running_traders:
x.status.set_stop_when_profit(False) instance.status.set_stop_when_profit(False)
broker.logger.log_this("Modified flag",2,f"{x.base}/{x.quote}") broker.logger.log_this("Modified flag",2,f"{instance.base}/{instance.quote}")
return jsonify({"Success": "Last call canceled"}) return jsonify({"Success": "Last call canceled"})
return jsonify({"Error": "No traders running"}) return jsonify({"Error": "No traders running"})
except Exception: except Exception:
@ -1873,56 +1873,56 @@ def unwrapped_add_quote(base,quote,amount):
json: A jsonified dictionary detailing the outcome of the operation. json: A jsonified dictionary detailing the outcome of the operation.
''' '''
for x in running_instances: for instance in running_traders:
if f"{base}/{quote}"==x.config.get_pair(): if f"{base}/{quote}"==instance.config.get_pair():
if x.config.get_is_short(): if instance.config.get_is_short():
return jsonify({"Error": "Quote can't be added to short traders"}) return jsonify({"Error": "Quote can't be added to short traders"})
x.pause = True instance.pause = True
new_average_price = (x.status.get_quote_spent()+float(amount))/(x.status.get_base_bought()+(float(amount)/x.status.get_price())) new_average_price = (instance.status.get_quote_spent()+float(amount))/(instance.status.get_base_bought()+(float(amount)/instance.status.get_price()))
broker.logger.log_this(f"Your new average buy price will be {new_average_price} {quote}",2,x.config.get_pair()) broker.logger.log_this(f"Your new average buy price will be {new_average_price} {quote}",2,instance.config.get_pair())
broker.logger.log_this(f"Your new take profit price price will be {new_average_price*x.get_tp_level()} {quote}",2,x.config.get_pair()) broker.logger.log_this(f"Your new take profit price price will be {new_average_price*instance.get_tp_level()} {quote}",2,instance.config.get_pair())
new_order = broker.new_market_order(x.config.get_pair(),float(amount),"buy") new_order = broker.new_market_order(instance.config.get_pair(),float(amount),"buy")
if new_order is None: if new_order is None:
broker.logger.log_this("Error: Market order returned None",2,x.config.get_pair()) broker.logger.log_this("Error: Market order returned None",2,instance.config.get_pair())
x.pause = False instance.pause = False
return jsonify({"Error": "Market order returned None"}) return jsonify({"Error": "Market order returned None"})
while True: while True:
time.sleep(broker.get_wait_time()) time.sleep(broker.get_wait_time())
returned_order = broker.get_order(new_order["id"],x.config.get_pair()) returned_order = broker.get_order(new_order["id"],instance.config.get_pair())
if returned_order==broker.empty_order: if returned_order==broker.empty_order:
broker.logger.log_this("Problems sending the order",2,x.config.get_pair()) broker.logger.log_this("Problems sending the order",2,instance.config.get_pair())
x.pause = False instance.pause = False
return jsonify({"Error": "Problems sending the order"}) return jsonify({"Error": "Problems sending the order"})
elif returned_order["status"]=="expired": elif returned_order["status"]=="expired":
x.pause = False instance.pause = False
return jsonify({"Error": "New order expired"}) return jsonify({"Error": "New order expired"})
elif returned_order["status"]=="closed": elif returned_order["status"]=="closed":
broker.logger.log_this("Order sent",2,x.config.get_pair()) broker.logger.log_this("Order sent",2,instance.config.get_pair())
new_fees_in_base, new_fees_in_quote = x.parse_fees(returned_order) new_fees_in_base, new_fees_in_quote = instance.parse_fees(returned_order)
x.status.set_fees_paid_in_base(x.status.get_fees_paid_in_base() + new_fees_in_base) instance.status.set_fees_paid_in_base(instance.status.get_fees_paid_in_base() + new_fees_in_base)
x.status.set_fees_paid_in_quote(x.status.get_fees_paid_in_quote() + new_fees_in_quote) instance.status.set_fees_paid_in_quote(instance.status.get_fees_paid_in_quote() + new_fees_in_quote)
x.status.set_base_bought(x.status.get_base_bought() + returned_order["filled"] - new_fees_in_base) instance.status.set_base_bought(instance.status.get_base_bought() + returned_order["filled"] - new_fees_in_base)
x.status.set_quote_spent(x.status.get_quote_spent()+returned_order["cost"]) instance.status.set_quote_spent(instance.status.get_quote_spent()+returned_order["cost"])
broker.logger.log_this("Cancelling old take profit order and sending a new one",2,x.config.get_pair()) broker.logger.log_this("Cancelling old take profit order and sending a new one",2,instance.config.get_pair())
attempts = 5 attempts = 5
while broker.cancel_order(x.status.get_take_profit_order()["id"],x.config.get_pair())==1: while broker.cancel_order(instance.status.get_take_profit_order()["id"],instance.config.get_pair())==1:
broker.logger.log_this("Can't cancel old take profit order, retrying...",2,x.config.get_pair()) broker.logger.log_this("Can't cancel old take profit order, retrying...",2,instance.config.get_pair())
time.sleep(broker.get_wait_time()) time.sleep(broker.get_wait_time())
attempts-=1 attempts-=1
if attempts==0: if attempts==0:
broker.logger.log_this("Can't cancel old take profit order, cancelling...",2,x.config.get_pair()) broker.logger.log_this("Can't cancel old take profit order, cancelling...",2,instance.config.get_pair())
x.pause = False instance.pause = False
return jsonify({"Error": "Can't cancel old take profit order."}) return jsonify({"Error": "Can't cancel old take profit order."})
x.status.set_take_profit_price(x.status.get_quote_spent()/x.status.get_base_bought()*x.get_tp_level()) instance.status.set_take_profit_price(instance.status.get_quote_spent()/instance.status.get_base_bought()*instance.get_tp_level())
x.status.set_take_profit_order(broker.new_limit_order(x.config.get_pair(),x.status.get_base_bought(),"sell",x.status.get_take_profit_price())) instance.status.set_take_profit_order(broker.new_limit_order(instance.config.get_pair(),instance.status.get_base_bought(),"sell",instance.status.get_take_profit_price()))
x.update_status(True) instance.update_status(True)
break break
else: else:
broker.logger.log_this("Waiting for initial order to get filled",2,x.config.get_pair()) broker.logger.log_this("Waiting for initial order to get filled",2,instance.config.get_pair())
broker.logger.log_this(f"{returned_order}",2,x.config.get_pair()) broker.logger.log_this(f"{returned_order}",2,instance.config.get_pair())
time.sleep(broker.get_wait_time()) time.sleep(broker.get_wait_time())
x.pause = False instance.pause = False
broker.logger.log_this("Done",2,x.config.get_pair()) broker.logger.log_this("Done",2,instance.config.get_pair())
return jsonify({"Success": "Quote added successfully"}) return jsonify({"Success": "Quote added successfully"})
return jsonify({"Error": "Something horrible happened :S"}) return jsonify({"Error": "Something horrible happened :S"})
@ -1936,7 +1936,7 @@ def unwrapped_missing_pairs():
''' '''
try: try:
missing_pairs = broker.get_pairs() missing_pairs = broker.get_pairs()
for trader in running_instances: for trader in running_traders:
if f"{trader.base}{trader.quote}" in missing_pairs: if f"{trader.base}{trader.quote}" in missing_pairs:
missing_pairs.remove(f"{trader.base}{trader.quote}") missing_pairs.remove(f"{trader.base}{trader.quote}")
return jsonify({"Success": missing_pairs}) return jsonify({"Success": missing_pairs})
@ -1959,10 +1959,10 @@ def unwrapped_toggle_cleanup(base,quote):
try: try:
pair_to_toggle = f"{base}/{quote}" pair_to_toggle = f"{base}/{quote}"
for x in running_instances: for instance in running_traders:
if pair_to_toggle==x.config.get_pair(): if pair_to_toggle==instance.config.get_pair():
x.config.set_cleanup(not x.config.get_cleanup()) instance.config.set_cleanup(not instance.config.get_cleanup())
if x.config.get_cleanup(): if instance.config.get_cleanup():
return jsonify({"Success": "Cleanup turned ON"}) return jsonify({"Success": "Cleanup turned ON"})
return jsonify({"Success": "Cleanup turned OFF"}) return jsonify({"Success": "Cleanup turned OFF"})
except Exception as e: except Exception as e:
@ -1985,15 +1985,15 @@ def unwrapped_toggle_autoswitch(base,quote):
try: try:
pair_to_toggle = f"{base}/{quote}" pair_to_toggle = f"{base}/{quote}"
for x in running_instances: for instance in running_traders:
if pair_to_toggle==x.config.get_pair(): if pair_to_toggle==instance.config.get_pair():
if x.config.get_autoswitch(): if instance.config.get_autoswitch():
broker.logger.log_this("Autoswitch turned OFF",1,f"{base}/{quote}") broker.logger.log_this("Autoswitch turned OFF",1,f"{base}/{quote}")
x.config.set_autoswitch(False) instance.config.set_autoswitch(False)
return jsonify({"Success": "Autoswitch is now OFF"}) return jsonify({"Success": "Autoswitch is now OFF"})
else: else:
broker.logger.log_this("Autoswitch turned ON",1,f"{base}/{quote}") broker.logger.log_this("Autoswitch turned ON",1,f"{base}/{quote}")
x.config.set_autoswitch(True) instance.config.set_autoswitch(True)
return jsonify({"Success": "Autoswitch is now ON"}) return jsonify({"Success": "Autoswitch is now ON"})
except Exception as e: except Exception as e:
broker.logger.log_this(f"Exception while toggling autoswitch: {e}",1,f"{base}{quote}") broker.logger.log_this(f"Exception while toggling autoswitch: {e}",1,f"{base}{quote}")
@ -2013,15 +2013,15 @@ def unwrapped_toggle_liquidate_after_switch(base,quote):
try: try:
pair_to_toggle = f"{base}/{quote}" pair_to_toggle = f"{base}/{quote}"
for x in running_instances: for instance in running_traders:
if pair_to_toggle==x.config.get_pair(): if pair_to_toggle==instance.config.get_pair():
if x.config.get_liquidate_after_switch(): if instance.config.get_liquidate_after_switch():
broker.logger.log_this("Liquidate after switch turned OFF",1,f"{base}/{quote}") broker.logger.log_this("Liquidate after switch turned OFF",1,f"{base}/{quote}")
x.config.set_liquidate_after_switch(False) instance.config.set_liquidate_after_switch(False)
return jsonify({"Success": "Liquidate after switch is now OFF"}) return jsonify({"Success": "Liquidate after switch is now OFF"})
else: else:
broker.logger.log_this("Liquidate after switch turned ON",1,f"{base}/{quote}") broker.logger.log_this("Liquidate after switch turned ON",1,f"{base}/{quote}")
x.config.set_liquidate_after_switch(True) instance.config.set_liquidate_after_switch(True)
return jsonify({"Success": "Liquidate after switch is now ON"}) return jsonify({"Success": "Liquidate after switch is now ON"})
except Exception as e: except Exception as e:
broker.logger.log_this(f"Exception while toggling liquidate after switch: {e}",1,f"{base}{quote}") broker.logger.log_this(f"Exception while toggling liquidate after switch: {e}",1,f"{base}{quote}")
@ -2041,15 +2041,15 @@ def unwrapped_toggle_check_old_long_price(base,quote):
try: try:
pair_to_toggle = f"{base}/{quote}" pair_to_toggle = f"{base}/{quote}"
for x in running_instances: for instance in running_traders:
if pair_to_toggle==x.config.get_pair(): if pair_to_toggle==instance.config.get_pair():
if x.config.get_check_old_long_price(): if instance.config.get_check_old_long_price():
broker.logger.log_this("Check OFF",1,f"{base}/{quote}") broker.logger.log_this("Check OFF",1,f"{base}/{quote}")
x.config.set_check_old_long_price(False) instance.config.set_check_old_long_price(False)
return jsonify({"Success": "Old long price check turned OFF"}) return jsonify({"Success": "Old long price check turned OFF"})
else: else:
broker.logger.log_this("Check ON",1,f"{base}/{quote}") broker.logger.log_this("Check ON",1,f"{base}/{quote}")
x.config.set_check_old_long_price(True) instance.config.set_check_old_long_price(True)
return jsonify({"Success": "Old long price check turned ON"}) return jsonify({"Success": "Old long price check turned ON"})
except Exception as e: except Exception as e:
broker.logger.log_this(f"Exception while toggling check_old_long_price: {e}",1,f"{base}{quote}") broker.logger.log_this(f"Exception while toggling check_old_long_price: {e}",1,f"{base}{quote}")
@ -2071,7 +2071,7 @@ def unwrapped_switch_quote_currency(base,quote,new_quote):
try: try:
pair_to_switch = f"{base}/{quote}" pair_to_switch = f"{base}/{quote}"
for trader in running_instances: for trader in running_traders:
if pair_to_switch==trader.config.get_pair(): if pair_to_switch==trader.config.get_pair():
#Pause the trader #Pause the trader
trader.pause = True trader.pause = True
@ -2142,7 +2142,7 @@ def unwrapped_trader_time():
''' '''
try: try:
return jsonify({"Time": max(x.last_time_seen for x in running_instances)}) return jsonify({"Time": max(instance.last_time_seen for instance in running_traders)})
except Exception as e: except Exception as e:
broker.logger.log_this(f"Exception while retrieving trader_time: {e}",1) broker.logger.log_this(f"Exception while retrieving trader_time: {e}",1)
return jsonify({"Error": str(e)}) return jsonify({"Error": str(e)})
@ -2252,7 +2252,7 @@ def unwrapped_reload_safety_order(base,quote):
jsonify: A jsonified dictionary detailing the outcome of the operation. jsonify: A jsonified dictionary detailing the outcome of the operation.
''' '''
try: try:
for trader in running_instances: for trader in running_traders:
if trader.config.get_pair()==f"{base}/{quote}": if trader.config.get_pair()==f"{base}/{quote}":
trader.config.load_from_file() trader.config.load_from_file()
return jsonify({"Success": "Safety order reloaded successfully"}) return jsonify({"Success": "Safety order reloaded successfully"})
@ -2294,7 +2294,7 @@ def unwrapped_reload_trader_config(base,quote):
Returns: Returns:
jsonify: A jsonified dictionary detailing the outcome of the operation. jsonify: A jsonified dictionary detailing the outcome of the operation.
''' '''
for trader in running_instances: for trader in running_traders:
if trader.config.get_pair() == f"{base}/{quote}": if trader.config.get_pair() == f"{base}/{quote}":
return jsonify(worker_status[f"{base}/{quote}"]) return jsonify(worker_status[f"{base}/{quote}"])
return jsonify({"Error": "Worker does not exist"}) return jsonify({"Error": "Worker does not exist"})
@ -2340,7 +2340,7 @@ if __name__=="__main__":
broker = exchange_wrapper.Broker(exchange,read_config,sys.argv[1]) #Also passes the config filename broker = exchange_wrapper.Broker(exchange,read_config,sys.argv[1]) #Also passes the config filename
#Declaring some variables #Declaring some variables
running_instances = [] running_traders = []
open_orders = [] open_orders = []
instances_to_add = [] instances_to_add = []
online_pairs = [] online_pairs = []