imported_trader now takes order ids

This commit is contained in:
Nicolás Sánchez 2025-03-19 16:04:06 -03:00
parent fa51e1d97a
commit a19cf0271c
4 changed files with 31 additions and 13 deletions

View File

@ -1,3 +1,6 @@
2025.03.19:
. Added the possibility to force specific orders when importing a trader.
2025.03.07: 2025.03.07:
. Error fix in take_profit_routine. . Error fix in take_profit_routine.

18
main.py
View File

@ -16,7 +16,7 @@ import exchange_wrapper
import trader import trader
version = "2025.03.07" version = "2025.03.19"
''' '''
Color definitions. If you want to change them, check the reference at https://en.wikipedia.org/wiki/ANSI_escape_code#Colors Color definitions. If you want to change them, check the reference at https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
@ -72,7 +72,7 @@ def time_to_unix(year: str, month: str, day: str) -> int:
return 0 return 0
def import_instance(base: str, quote: str) -> int: def import_instance(base: str, quote: str, forced_tp_id = None, forced_so_id = None) -> int:
''' '''
Imports an previously running trader instance from the status file. Imports an previously running trader instance from the status file.
@ -84,7 +84,7 @@ def import_instance(base: str, quote: str) -> int:
int: 0 if successful int: 0 if successful
''' '''
broker.logger.log_this(f"Importing {base}/{quote}") broker.logger.log_this(f"Importing {base}/{quote}")
instances_to_add.append(trader.trader(broker,f"{base}/{quote}",is_import=True)) instances_to_add.append(trader.trader(broker,f"{base}/{quote}",is_import=True,forced_tp_id=forced_tp_id,forced_so_id=forced_so_id))
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
@ -630,6 +630,8 @@ def import_pair():
Parameters: Parameters:
base: str base: str
quote: str quote: str
forced_tp_id: str
forced_so_id: str
''' '''
if "X-API-KEY" in request.headers and request.headers.get("X-API-KEY") in valid_keys: if "X-API-KEY" in request.headers and request.headers.get("X-API-KEY") in valid_keys:
@ -639,7 +641,9 @@ def import_pair():
data = request.json data = request.json
base = data["base"] base = data["base"]
quote = data["quote"] quote = data["quote"]
return unwrapped_import_pair(base,quote) forced_tp_id = data["forced_tp_id"] if "forced_tp_id" in data else None
forced_so_id = data["forced_so_id"] if "forced_so_id" in data else None
return unwrapped_import_pair(base,quote,forced_tp_id,forced_so_id)
except Exception as e: except Exception as e:
print(e) print(e)
return jsonify({'Error': 'Halp'}) return jsonify({'Error': 'Halp'})
@ -1389,20 +1393,22 @@ def unwrapped_restart_pair(base,quote):
return jsonify({"Error": "Halp"}) return jsonify({"Error": "Halp"})
def unwrapped_import_pair(base,quote): def unwrapped_import_pair(base,quote,forced_tp_id = None, forced_so_id = None):
''' '''
Imports a previously running pair Imports a previously running pair
Parameters: Parameters:
base (str): The base currency of the pair base (str): The base currency of the pair
quote (str): The quote currency of the pair quote (str): The quote currency of the pair
forced_tp_id (str): The ID of the take profit order to use
forced_so_id (str): The ID of the stop order to use
Returns: Returns:
jsonified dictionary detailing the outcome of the operation. jsonified dictionary detailing the outcome of the operation.
''' '''
try: try:
import_instance(base,quote) import_instance(base,quote,forced_tp_id,forced_so_id)
broker.add_pair_to_config(f"{base}{quote}") broker.add_pair_to_config(f"{base}{quote}")
broker.rewrite_config_file() broker.rewrite_config_file()
broker.logger.log_this(f"Done",2,f"{base}/{quote}") broker.logger.log_this(f"Done",2,f"{base}/{quote}")

View File

@ -6,7 +6,7 @@ from config_handler import ConfigHandler
from status_handler import StatusHandler from status_handler import StatusHandler
class trader: class trader:
def __init__(self, broker, pair: str, is_import: bool = False): def __init__(self, broker, pair: str, is_import: bool = False, forced_tp_id = None, forced_so_id = None):
#Flags #Flags
self.pause = True self.pause = True
@ -42,7 +42,7 @@ class trader:
self.status.set_pause_reason("Initialization") self.status.set_pause_reason("Initialization")
if is_import: if is_import:
self.load_imported_trader() self.load_imported_trader(forced_tp_order_id=forced_tp_id, forced_safety_order_id=forced_so_id)
return None return None
# An alternative would be to set up a variable like self.is_initalized to false and finish the initialization here. # An alternative would be to set up a variable like self.is_initalized to false and finish the initialization here.
@ -1573,7 +1573,7 @@ class trader:
return f"{white}{line1}\n{line3}{white}" return f"{white}{line1}\n{line3}{white}"
def load_imported_trader(self) -> int: def load_imported_trader(self, forced_tp_order_id = None, forced_safety_order_id = None) -> int:
''' '''
Loads status dictionary, orders and sets up variables Loads status dictionary, orders and sets up variables
''' '''
@ -1587,14 +1587,16 @@ class trader:
self.config.set_no_of_safety_orders(self.status.get_no_of_safety_orders()) #If this is not loaded from status_dict, it will ignore if safety orders were added at runtime self.config.set_no_of_safety_orders(self.status.get_no_of_safety_orders()) #If this is not loaded from status_dict, it will ignore if safety orders were added at runtime
#Refresh take profit order #Refresh take profit order
self.status.set_take_profit_order(self.broker.get_order(self.status.get_take_profit_order()["id"],self.config.get_pair())) order_id = self.status.get_take_profit_order()["id"] if forced_tp_order_id is None else forced_tp_order_id
self.status.set_take_profit_order(self.broker.get_order(order_id,self.config.get_pair()))
if self.status.get_take_profit_order()==self.broker.get_empty_order(): if self.status.get_take_profit_order()==self.broker.get_empty_order():
self.broker.logger.log_this("Couldn't load take profit order (broker returned empty order). Aborting.",1,self.config.get_pair()) self.broker.logger.log_this("Couldn't load take profit order (broker returned empty order). Aborting.",1,self.config.get_pair())
self.quit = True self.quit = True
return 1 return 1
#Refresh safety order #Refresh safety order
self.status.set_safety_order(self.broker.get_order(self.status.get_safety_order()["id"],self.config.get_pair())) order_id = self.status.get_safety_order()["id"] if forced_safety_order_id is None else forced_safety_order_id
self.status.set_safety_order(self.broker.get_order(order_id,self.config.get_pair()))
if self.status.get_safety_order()==self.broker.get_empty_order() and self.status.get_so_amount()<self.config.get_no_of_safety_orders(): if self.status.get_safety_order()==self.broker.get_empty_order() and self.status.get_so_amount()<self.config.get_no_of_safety_orders():
#The second condition is important: it signals that the empty order returned was because of an error, not because the trader ran out of funds in the past. #The second condition is important: it signals that the empty order returned was because of an error, not because the trader ran out of funds in the past.
#When the trader runs out of funds, safety_order_index=config.get_no_of_safety_orders() #When the trader runs out of funds, safety_order_index=config.get_no_of_safety_orders()

View File

@ -515,6 +515,11 @@ 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")
break break
@ -522,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 ")