From 70e9fa6136a0d7705dfe6a72e0315467d6c0a838 Mon Sep 17 00:00:00 2001 From: hippocritical Date: Tue, 27 Dec 2022 20:14:39 +0100 Subject: [PATCH 001/229] implementing the strategy_updater in a first version --- freqtrade/commands/__init__.py | 1 + freqtrade/commands/arguments.py | 14 +- freqtrade/commands/strategy_utils_commands.py | 37 +++ freqtrade/strategy/strategy_updater.py | 213 ++++++++++++++++++ 4 files changed, 263 insertions(+), 2 deletions(-) create mode 100644 freqtrade/commands/strategy_utils_commands.py create mode 100644 freqtrade/strategy/strategy_updater.py diff --git a/freqtrade/commands/__init__.py b/freqtrade/commands/__init__.py index 788657cc8..66a9c995b 100644 --- a/freqtrade/commands/__init__.py +++ b/freqtrade/commands/__init__.py @@ -22,5 +22,6 @@ from freqtrade.commands.optimize_commands import (start_backtesting, start_backt start_edge, start_hyperopt) from freqtrade.commands.pairlist_commands import start_test_pairlist from freqtrade.commands.plot_commands import start_plot_dataframe, start_plot_profit +from freqtrade.commands.strategy_utils_commands import start_strategy_update from freqtrade.commands.trade_commands import start_trading from freqtrade.commands.webserver_commands import start_webserver diff --git a/freqtrade/commands/arguments.py b/freqtrade/commands/arguments.py index b53a1022d..9990ad230 100644 --- a/freqtrade/commands/arguments.py +++ b/freqtrade/commands/arguments.py @@ -115,6 +115,8 @@ NO_CONF_REQURIED = ["convert-data", "convert-trade-data", "download-data", "list NO_CONF_ALLOWED = ["create-userdir", "list-exchanges", "new-strategy"] +ARGS_STRATEGY_UTILS = ARGS_COMMON_OPTIMIZE + ["strategy_list"] + class Arguments: """ @@ -198,8 +200,8 @@ class Arguments: start_list_freqAI_models, start_list_markets, start_list_strategies, start_list_timeframes, start_new_config, start_new_strategy, start_plot_dataframe, - start_plot_profit, start_show_trades, start_test_pairlist, - start_trading, start_webserver) + start_plot_profit, start_show_trades, start_strategy_update, + start_test_pairlist, start_trading, start_webserver) subparsers = self.parser.add_subparsers(dest='command', # Use custom message when no subhandler is added @@ -440,3 +442,11 @@ class Arguments: parents=[_common_parser]) webserver_cmd.set_defaults(func=start_webserver) self._build_args(optionlist=ARGS_WEBSERVER, parser=webserver_cmd) + + # Add strategy_updater subcommand + strategy_updater_cmd = subparsers.add_parser('strategy-updater', + help='updates outdated strategy' + 'files to the current version', + parents=[_common_parser]) + strategy_updater_cmd.set_defaults(func=start_strategy_update) + self._build_args(optionlist=ARGS_STRATEGY_UTILS, parser=strategy_updater_cmd) diff --git a/freqtrade/commands/strategy_utils_commands.py b/freqtrade/commands/strategy_utils_commands.py new file mode 100644 index 000000000..b9431fecf --- /dev/null +++ b/freqtrade/commands/strategy_utils_commands.py @@ -0,0 +1,37 @@ +import logging +from typing import Any, Dict + +from freqtrade.configuration import setup_utils_configuration +from freqtrade.enums import RunMode +from freqtrade.resolvers import StrategyResolver + + +logger = logging.getLogger(__name__) + + +def start_strategy_update(args: Dict[str, Any]) -> None: + """ + Start the strategy updating script + :param args: Cli args from Arguments() + :return: None + """ + + # Import here to avoid loading backtesting module when it's not used + from freqtrade.strategy.strategy_updater import strategy_updater + + config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE) + + strategy_objs = StrategyResolver.search_all_objects( + config, enum_failed=True, recursive=config.get('recursive_strategy_search', False)) + + filtered_strategy_objs = [] + for args_strategy in args['strategy_list']: + for strategy_obj in strategy_objs: + if strategy_obj['name'] == args_strategy and strategy_obj not in filtered_strategy_objs: + filtered_strategy_objs.append(strategy_obj) + break + + for filtered_strategy_obj in filtered_strategy_objs: + # Initialize backtesting object + instance_strategy_updater = strategy_updater() + strategy_updater.start(instance_strategy_updater, filtered_strategy_obj) diff --git a/freqtrade/strategy/strategy_updater.py b/freqtrade/strategy/strategy_updater.py new file mode 100644 index 000000000..fea8edf31 --- /dev/null +++ b/freqtrade/strategy/strategy_updater.py @@ -0,0 +1,213 @@ +import ast +import os +import shutil + + +class strategy_updater: + name_mapping = { + 'ticker_interval': 'timeframe', + 'buy': 'enter_long', + 'sell': 'exit_long', + 'buy_tag': 'enter_tag', + 'sell_reason': 'exit_reason', + + 'sell_signal': 'exit_signal', + 'custom_sell': 'custom_exit', + 'force_sell': 'force_exit', + 'emergency_sell': 'emergency_exit', + + # Strategy/config settings: + 'use_sell_signal': 'use_exit_signal', + 'sell_profit_only': 'exit_profit_only', + 'sell_profit_offset': 'exit_profit_offset', + 'ignore_roi_if_buy_signal': 'ignore_roi_if_entry_signal', + 'forcebuy_enable': 'force_entry_enable', + } + + function_mapping = { + 'populate_buy_trend': 'populate_entry_trend', + 'populate_sell_trend': 'populate_exit_trend', + 'custom_sell': 'custom_exit', + 'check_buy_timeout': 'check_entry_timeout', + 'check_sell_timeout': 'check_exit_timeout', + # '': '', + } + # order_time_in_force, order_types, unfilledtimeout + otif_ot_unfilledtimeout = { + 'buy': 'entry', + 'sell': 'exit', + } + + # create a dictionary that maps the old column names to the new ones + rename_dict = {'buy': 'enter_long', 'sell': 'exit_long', 'buy_tag': 'enter_tag'} + + def start(self, strategy_obj: dict) -> None: + """ + Run strategy updater + It updates a strategy to v3 with the help of the ast-module + :return: None + """ + + self.cwd = os.getcwd() + self.strategies_backup_folder = f'{os.getcwd()}user_data/strategies_orig_updater' + source_file = strategy_obj['location'] + + # read the file + with open(source_file, 'r') as f: + old_code = f.read() + if not os.path.exists(self.strategies_backup_folder): + os.makedirs(self.strategies_backup_folder) + + # backup original + # => currently no date after the filename, + # could get overridden pretty fast if this is fired twice! + shutil.copy(source_file, f"{self.strategies_backup_folder}/{strategy_obj['location_rel']}") + + # update the code + new_code = strategy_updater.update_code(self, old_code, + strategy_updater.name_mapping, + strategy_updater.function_mapping, + strategy_updater.rename_dict) + + # write the modified code to the destination folder + with open(source_file, 'w') as f: + f.write(new_code) + print(f"conversion of file {source_file} successful.") + + # define the function to update the code + def update_code(self, code, _name_mapping, _function_mapping, _rename_dict): + # parse the code into an AST + tree = ast.parse(code) + + # use the AST to update the code + updated_code = strategy_updater.modify_ast( + tree, + _name_mapping, + _function_mapping, + _rename_dict) + + # return the modified code without executing it + return updated_code + + # function that uses the ast module to update the code + def modify_ast(node, _name_mapping, _function_mapping, _rename_dict): # noqa + # create a visitor that will update the names and functions + class NameUpdater(ast.NodeTransformer): + def generic_visit(self, node): + # traverse the AST recursively by calling the visitor method for each child node + if hasattr(node, "_fields"): + for field_name, field_value in ast.iter_fields(node): + self.check_fields(field_value) + self.check_strategy_and_config_settings(field_value) + # add this check to handle the case where field_value is a slice + if isinstance(field_value, ast.Slice): + self.visit(field_value) + # add this check to handle the case where field_value is a target + if isinstance(field_value, ast.expr_context): + self.visit(field_value) + + def check_fields(self, field_value): + if isinstance(field_value, list): + for item in field_value: + if isinstance(item, ast.AST): + self.visit(item) + + def check_strategy_and_config_settings(self, field_value): + if (isinstance(field_value, ast.AST) and + hasattr(node, "targets") and + isinstance(node.targets, list)): + for target in node.targets: + if (hasattr(target, "id") and + (target.id == "order_time_in_force" or + target.id == "order_types" or + target.id == "unfilledtimeout") and + hasattr(field_value, "keys") and + isinstance(field_value.keys, list)): + for key in field_value.keys: + self.visit(key) + + def visit_Name(self, node): + # if the name is in the mapping, update it + if node.id in _name_mapping: + node.id = _name_mapping[node.id] + return node + + def visit_Import(self, node): + # do not update the names in import statements + return node + + def visit_ImportFrom(self, node): + # do not update the names in import statements + if hasattr(node, "module"): + if node.module == "freqtrade.strategy.hyper": + node.module = "freqtrade.strategy" + return node + + def visit_FunctionDef(self, node): + # if the function name is in the mapping, update it + if node.name in _function_mapping: + node.name = _function_mapping[node.name] + return self.generic_visit(node) + + def visit_Attribute(self, node): + # if the attribute name is 'nr_of_successful_buys', + # update it to 'nr_of_successful_entries' + if isinstance(node.value, ast.Name) and \ + node.value.id == 'trades' and \ + node.attr == 'nr_of_successful_buys': + node.attr = 'nr_of_successful_entries' + return self.generic_visit(node) + + def visit_ClassDef(self, node): + # check if the class is derived from IStrategy + if any(isinstance(base, ast.Name) and + base.id == 'IStrategy' for base in node.bases): + # check if the INTERFACE_VERSION variable exists + has_interface_version = any( + isinstance(child, ast.Assign) and + isinstance(child.targets[0], ast.Name) and + child.targets[0].id == 'INTERFACE_VERSION' + for child in node.body + ) + + # if the INTERFACE_VERSION variable does not exist, add it as the first child + if not has_interface_version: + node.body.insert(0, ast.parse('INTERFACE_VERSION = 3').body[0]) + # otherwise, update its value to 3 + else: + for child in node.body: + if isinstance(child, ast.Assign) and \ + isinstance(child.targets[0], ast.Name) and \ + child.targets[0].id == 'INTERFACE_VERSION': + child.value = ast.parse('3').body[0].value + return self.generic_visit(node) + + def visit_Subscript(self, node): + if isinstance(node.slice, ast.Constant): + if node.slice.value in strategy_updater.rename_dict: + # Replace the slice attributes with the values from rename_dict + node.slice.value = strategy_updater.rename_dict[node.slice.value] + if hasattr(node.slice, "elts"): + for elt in node.slice.elts: + if isinstance(elt, ast.Constant) and \ + elt.value in strategy_updater.rename_dict: + elt.value = strategy_updater.rename_dict[elt.value] + return node + + def visit_Constant(self, node): + # do not update the names in import statements + if node.value in \ + strategy_updater.otif_ot_unfilledtimeout: + node.value = \ + strategy_updater.otif_ot_unfilledtimeout[node.value] + return node + + # use the visitor to update the names and functions in the AST + NameUpdater().visit(node) + + # first fix the comments so it understands "\n" properly inside multi line comments. + ast.fix_missing_locations(node) + ast.increment_lineno(node, n=1) + + # generate the new code from the updated AST + return ast.unparse(node) From c6f045afa96c30bbd612af4b5877aeb41834d8fe Mon Sep 17 00:00:00 2001 From: hippocritical Date: Thu, 29 Dec 2022 22:17:52 +0100 Subject: [PATCH 002/229] fixing issues of the maintainer found a bug meaning elts could contain lists of elts (now recurively gone through) Next in line: writing tests based on StrategyUpdater.update_code --- freqtrade/commands/strategy_utils_commands.py | 6 +- freqtrade/strategy/strategy_updater.py | 213 ----------------- freqtrade/strategy/strategyupdater.py | 225 ++++++++++++++++++ 3 files changed, 228 insertions(+), 216 deletions(-) delete mode 100644 freqtrade/strategy/strategy_updater.py create mode 100644 freqtrade/strategy/strategyupdater.py diff --git a/freqtrade/commands/strategy_utils_commands.py b/freqtrade/commands/strategy_utils_commands.py index b9431fecf..13405089f 100644 --- a/freqtrade/commands/strategy_utils_commands.py +++ b/freqtrade/commands/strategy_utils_commands.py @@ -17,7 +17,7 @@ def start_strategy_update(args: Dict[str, Any]) -> None: """ # Import here to avoid loading backtesting module when it's not used - from freqtrade.strategy.strategy_updater import strategy_updater + from freqtrade.strategy.strategyupdater import StrategyUpdater config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE) @@ -33,5 +33,5 @@ def start_strategy_update(args: Dict[str, Any]) -> None: for filtered_strategy_obj in filtered_strategy_objs: # Initialize backtesting object - instance_strategy_updater = strategy_updater() - strategy_updater.start(instance_strategy_updater, filtered_strategy_obj) + instance_strategy_updater = StrategyUpdater() + StrategyUpdater.start(instance_strategy_updater, config, filtered_strategy_obj) diff --git a/freqtrade/strategy/strategy_updater.py b/freqtrade/strategy/strategy_updater.py deleted file mode 100644 index fea8edf31..000000000 --- a/freqtrade/strategy/strategy_updater.py +++ /dev/null @@ -1,213 +0,0 @@ -import ast -import os -import shutil - - -class strategy_updater: - name_mapping = { - 'ticker_interval': 'timeframe', - 'buy': 'enter_long', - 'sell': 'exit_long', - 'buy_tag': 'enter_tag', - 'sell_reason': 'exit_reason', - - 'sell_signal': 'exit_signal', - 'custom_sell': 'custom_exit', - 'force_sell': 'force_exit', - 'emergency_sell': 'emergency_exit', - - # Strategy/config settings: - 'use_sell_signal': 'use_exit_signal', - 'sell_profit_only': 'exit_profit_only', - 'sell_profit_offset': 'exit_profit_offset', - 'ignore_roi_if_buy_signal': 'ignore_roi_if_entry_signal', - 'forcebuy_enable': 'force_entry_enable', - } - - function_mapping = { - 'populate_buy_trend': 'populate_entry_trend', - 'populate_sell_trend': 'populate_exit_trend', - 'custom_sell': 'custom_exit', - 'check_buy_timeout': 'check_entry_timeout', - 'check_sell_timeout': 'check_exit_timeout', - # '': '', - } - # order_time_in_force, order_types, unfilledtimeout - otif_ot_unfilledtimeout = { - 'buy': 'entry', - 'sell': 'exit', - } - - # create a dictionary that maps the old column names to the new ones - rename_dict = {'buy': 'enter_long', 'sell': 'exit_long', 'buy_tag': 'enter_tag'} - - def start(self, strategy_obj: dict) -> None: - """ - Run strategy updater - It updates a strategy to v3 with the help of the ast-module - :return: None - """ - - self.cwd = os.getcwd() - self.strategies_backup_folder = f'{os.getcwd()}user_data/strategies_orig_updater' - source_file = strategy_obj['location'] - - # read the file - with open(source_file, 'r') as f: - old_code = f.read() - if not os.path.exists(self.strategies_backup_folder): - os.makedirs(self.strategies_backup_folder) - - # backup original - # => currently no date after the filename, - # could get overridden pretty fast if this is fired twice! - shutil.copy(source_file, f"{self.strategies_backup_folder}/{strategy_obj['location_rel']}") - - # update the code - new_code = strategy_updater.update_code(self, old_code, - strategy_updater.name_mapping, - strategy_updater.function_mapping, - strategy_updater.rename_dict) - - # write the modified code to the destination folder - with open(source_file, 'w') as f: - f.write(new_code) - print(f"conversion of file {source_file} successful.") - - # define the function to update the code - def update_code(self, code, _name_mapping, _function_mapping, _rename_dict): - # parse the code into an AST - tree = ast.parse(code) - - # use the AST to update the code - updated_code = strategy_updater.modify_ast( - tree, - _name_mapping, - _function_mapping, - _rename_dict) - - # return the modified code without executing it - return updated_code - - # function that uses the ast module to update the code - def modify_ast(node, _name_mapping, _function_mapping, _rename_dict): # noqa - # create a visitor that will update the names and functions - class NameUpdater(ast.NodeTransformer): - def generic_visit(self, node): - # traverse the AST recursively by calling the visitor method for each child node - if hasattr(node, "_fields"): - for field_name, field_value in ast.iter_fields(node): - self.check_fields(field_value) - self.check_strategy_and_config_settings(field_value) - # add this check to handle the case where field_value is a slice - if isinstance(field_value, ast.Slice): - self.visit(field_value) - # add this check to handle the case where field_value is a target - if isinstance(field_value, ast.expr_context): - self.visit(field_value) - - def check_fields(self, field_value): - if isinstance(field_value, list): - for item in field_value: - if isinstance(item, ast.AST): - self.visit(item) - - def check_strategy_and_config_settings(self, field_value): - if (isinstance(field_value, ast.AST) and - hasattr(node, "targets") and - isinstance(node.targets, list)): - for target in node.targets: - if (hasattr(target, "id") and - (target.id == "order_time_in_force" or - target.id == "order_types" or - target.id == "unfilledtimeout") and - hasattr(field_value, "keys") and - isinstance(field_value.keys, list)): - for key in field_value.keys: - self.visit(key) - - def visit_Name(self, node): - # if the name is in the mapping, update it - if node.id in _name_mapping: - node.id = _name_mapping[node.id] - return node - - def visit_Import(self, node): - # do not update the names in import statements - return node - - def visit_ImportFrom(self, node): - # do not update the names in import statements - if hasattr(node, "module"): - if node.module == "freqtrade.strategy.hyper": - node.module = "freqtrade.strategy" - return node - - def visit_FunctionDef(self, node): - # if the function name is in the mapping, update it - if node.name in _function_mapping: - node.name = _function_mapping[node.name] - return self.generic_visit(node) - - def visit_Attribute(self, node): - # if the attribute name is 'nr_of_successful_buys', - # update it to 'nr_of_successful_entries' - if isinstance(node.value, ast.Name) and \ - node.value.id == 'trades' and \ - node.attr == 'nr_of_successful_buys': - node.attr = 'nr_of_successful_entries' - return self.generic_visit(node) - - def visit_ClassDef(self, node): - # check if the class is derived from IStrategy - if any(isinstance(base, ast.Name) and - base.id == 'IStrategy' for base in node.bases): - # check if the INTERFACE_VERSION variable exists - has_interface_version = any( - isinstance(child, ast.Assign) and - isinstance(child.targets[0], ast.Name) and - child.targets[0].id == 'INTERFACE_VERSION' - for child in node.body - ) - - # if the INTERFACE_VERSION variable does not exist, add it as the first child - if not has_interface_version: - node.body.insert(0, ast.parse('INTERFACE_VERSION = 3').body[0]) - # otherwise, update its value to 3 - else: - for child in node.body: - if isinstance(child, ast.Assign) and \ - isinstance(child.targets[0], ast.Name) and \ - child.targets[0].id == 'INTERFACE_VERSION': - child.value = ast.parse('3').body[0].value - return self.generic_visit(node) - - def visit_Subscript(self, node): - if isinstance(node.slice, ast.Constant): - if node.slice.value in strategy_updater.rename_dict: - # Replace the slice attributes with the values from rename_dict - node.slice.value = strategy_updater.rename_dict[node.slice.value] - if hasattr(node.slice, "elts"): - for elt in node.slice.elts: - if isinstance(elt, ast.Constant) and \ - elt.value in strategy_updater.rename_dict: - elt.value = strategy_updater.rename_dict[elt.value] - return node - - def visit_Constant(self, node): - # do not update the names in import statements - if node.value in \ - strategy_updater.otif_ot_unfilledtimeout: - node.value = \ - strategy_updater.otif_ot_unfilledtimeout[node.value] - return node - - # use the visitor to update the names and functions in the AST - NameUpdater().visit(node) - - # first fix the comments so it understands "\n" properly inside multi line comments. - ast.fix_missing_locations(node) - ast.increment_lineno(node, n=1) - - # generate the new code from the updated AST - return ast.unparse(node) diff --git a/freqtrade/strategy/strategyupdater.py b/freqtrade/strategy/strategyupdater.py new file mode 100644 index 000000000..b62bc7822 --- /dev/null +++ b/freqtrade/strategy/strategyupdater.py @@ -0,0 +1,225 @@ +import ast +import os +import shutil +from pathlib import Path + +import astor + + +class StrategyUpdater: + name_mapping = { + 'ticker_interval': 'timeframe', + 'buy': 'enter_long', + 'sell': 'exit_long', + 'buy_tag': 'enter_tag', + 'sell_reason': 'exit_reason', + + 'sell_signal': 'exit_signal', + 'custom_sell': 'custom_exit', + 'force_sell': 'force_exit', + 'emergency_sell': 'emergency_exit', + + # Strategy/config settings: + 'use_sell_signal': 'use_exit_signal', + 'sell_profit_only': 'exit_profit_only', + 'sell_profit_offset': 'exit_profit_offset', + 'ignore_roi_if_buy_signal': 'ignore_roi_if_entry_signal', + 'forcebuy_enable': 'force_entry_enable', + } + + function_mapping = { + 'populate_buy_trend': 'populate_entry_trend', + 'populate_sell_trend': 'populate_exit_trend', + 'custom_sell': 'custom_exit', + 'check_buy_timeout': 'check_entry_timeout', + 'check_sell_timeout': 'check_exit_timeout', + # '': '', + } + # order_time_in_force, order_types, unfilledtimeout + otif_ot_unfilledtimeout = { + 'buy': 'entry', + 'sell': 'exit', + } + + # create a dictionary that maps the old column names to the new ones + rename_dict = {'buy': 'enter_long', 'sell': 'exit_long', 'buy_tag': 'enter_tag'} + + def start(self, config, strategy_obj: dict) -> None: + """ + Run strategy updater + It updates a strategy to v3 with the help of the ast-module + :return: None + """ + + source_file = strategy_obj['location'] + strategies_backup_folder = Path.joinpath(config['user_data_dir'], "strategies_orig_updater") + target_file = Path.joinpath(strategies_backup_folder, strategy_obj['location_rel']) + + # read the file + with open(source_file, 'r') as f: + old_code = f.read() + if not os.path.exists(strategies_backup_folder): + os.makedirs(strategies_backup_folder) + + # backup original + # => currently no date after the filename, + # could get overridden pretty fast if this is fired twice! + # The folder is always the same and the file name too (currently). + shutil.copy(source_file, target_file) + + # update the code + new_code = StrategyUpdater.update_code(self, old_code) + + # write the modified code to the destination folder + with open(source_file, 'w') as f: + f.write(new_code) + print(f"conversion of file {source_file} successful.") + + # define the function to update the code + def update_code(self, code): + # parse the code into an AST + tree = ast.parse(code) + + # use the AST to update the code + updated_code = self.modify_ast( + tree) + + # return the modified code without executing it + return updated_code + + # function that uses the ast module to update the code + def modify_ast(self, tree): # noqa + # use the visitor to update the names and functions in the AST + NameUpdater().visit(tree) + + # first fix the comments, so it understands "\n" properly inside multi line comments. + ast.fix_missing_locations(tree) + ast.increment_lineno(tree, n=1) + + # generate the new code from the updated AST + return astor.to_source(tree) + + +# Here we go through each respective node, slice, elt, key ... to replace outdated entries. +class NameUpdater(ast.NodeTransformer): + def generic_visit(self, node): + # traverse the AST recursively by calling the visitor method for each child node + if hasattr(node, "_fields"): + for field_name, field_value in ast.iter_fields(node): + self.visit(field_value) + self.generic_visit(field_value) + self.check_fields(field_value) + self.check_strategy_and_config_settings(node, field_value) + # add this check to handle the case where field_value is a slice + if isinstance(field_value, ast.Slice): + self.visit(field_value) + # add this check to handle the case where field_value is a target + if isinstance(field_value, ast.expr_context): + self.visit(field_value) + + def check_fields(self, field_value): + if isinstance(field_value, list): + for item in field_value: + if isinstance(item, ast.AST): + self.visit(item) + + def check_strategy_and_config_settings(self, node, field_value): + if (isinstance(field_value, ast.AST) and + hasattr(node, "targets") and + isinstance(node.targets, list)): + for target in node.targets: + if (hasattr(target, "id") and + hasattr(field_value, "keys") and + isinstance(field_value.keys, list)): + if (target.id == "order_time_in_force" or + target.id == "order_types" or + target.id == "unfilledtimeout"): + for key in field_value.keys: + self.visit(key) + # Check if the target is a Subscript object with a "value" attribute + if isinstance(target, ast.Subscript) and hasattr(target.value, "attr"): + if target.value.attr == "loc": + self.visit(target) + + def visit_Name(self, node): + # if the name is in the mapping, update it + if node.id in StrategyUpdater.name_mapping: + node.id = StrategyUpdater.name_mapping[node.id] + return node + + def visit_Import(self, node): + # do not update the names in import statements + return node + + def visit_ImportFrom(self, node): + # do not update the names in import statements + if hasattr(node, "module"): + if node.module == "freqtrade.strategy.hyper": + node.module = "freqtrade.strategy" + return node + + def visit_FunctionDef(self, node): + # if the function name is in the mapping, update it + if node.name in StrategyUpdater.function_mapping: + node.name = StrategyUpdater.function_mapping[node.name] + return self.generic_visit(node) + + def visit_Attribute(self, node): + # if the attribute name is 'nr_of_successful_buys', + # update it to 'nr_of_successful_entries' + if isinstance(node.value, ast.Name) and \ + node.value.id == 'trades' and \ + node.attr == 'nr_of_successful_buys': + node.attr = 'nr_of_successful_entries' + return self.generic_visit(node) + + def visit_ClassDef(self, node): + # check if the class is derived from IStrategy + if any(isinstance(base, ast.Name) and + base.id == 'IStrategy' for base in node.bases): + # check if the INTERFACE_VERSION variable exists + has_interface_version = any( + isinstance(child, ast.Assign) and + isinstance(child.targets[0], ast.Name) and + child.targets[0].id == 'INTERFACE_VERSION' + for child in node.body + ) + + # if the INTERFACE_VERSION variable does not exist, add it as the first child + if not has_interface_version: + node.body.insert(0, ast.parse('INTERFACE_VERSION = 3').body[0]) + # otherwise, update its value to 3 + else: + for child in node.body: + if isinstance(child, ast.Assign) and \ + isinstance(child.targets[0], ast.Name) and \ + child.targets[0].id == 'INTERFACE_VERSION': + child.value = ast.parse('3').body[0].value + return self.generic_visit(node) + + def visit_Subscript(self, node): + if isinstance(node.slice, ast.Constant): + if node.slice.value in StrategyUpdater.rename_dict: + # Replace the slice attributes with the values from rename_dict + node.slice.value = StrategyUpdater.rename_dict[node.slice.value] + if hasattr(node.slice, "elts"): + self.visit_slice_elts(node.slice.elts) + if hasattr(node.slice.value, "elts"): + self.visit_slice_elts(node.slice.value.elts) + return node + + # elts can have elts (technically recursively) + def visit_slice_elts(self, elts): + for elt in elts: + if isinstance(elt, ast.Constant) and elt.value in StrategyUpdater.rename_dict: + elt.value = StrategyUpdater.rename_dict[elt.value] + elif hasattr(elt, "elts"): + self.visit_slice_elts(elt.elts) + + def visit_Constant(self, node): + # do not update the names in import statements + if node.value in \ + StrategyUpdater.otif_ot_unfilledtimeout: + node.value = \ + StrategyUpdater.otif_ot_unfilledtimeout[node.value] + return node From 82218d01f48051e2a43ad097a7453f3a1da533ac Mon Sep 17 00:00:00 2001 From: hippocritical Date: Fri, 30 Dec 2022 21:48:06 +0100 Subject: [PATCH 003/229] sped up the function generic_visit that now skips unnecessary fields added mentioning of skipped class names since they could not be found --- freqtrade/commands/strategy_utils_commands.py | 5 +++-- freqtrade/strategy/strategyupdater.py | 8 ++++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/freqtrade/commands/strategy_utils_commands.py b/freqtrade/commands/strategy_utils_commands.py index 13405089f..cf7ba5e13 100644 --- a/freqtrade/commands/strategy_utils_commands.py +++ b/freqtrade/commands/strategy_utils_commands.py @@ -25,11 +25,12 @@ def start_strategy_update(args: Dict[str, Any]) -> None: config, enum_failed=True, recursive=config.get('recursive_strategy_search', False)) filtered_strategy_objs = [] - for args_strategy in args['strategy_list']: - for strategy_obj in strategy_objs: + for strategy_obj in strategy_objs: + for args_strategy in args['strategy_list']: if strategy_obj['name'] == args_strategy and strategy_obj not in filtered_strategy_objs: filtered_strategy_objs.append(strategy_obj) break + print(f"strategy {strategy_obj['name']} could not be loaded or found and is skipped.") for filtered_strategy_obj in filtered_strategy_objs: # Initialize backtesting object diff --git a/freqtrade/strategy/strategyupdater.py b/freqtrade/strategy/strategyupdater.py index b62bc7822..74bb4454c 100644 --- a/freqtrade/strategy/strategyupdater.py +++ b/freqtrade/strategy/strategyupdater.py @@ -52,6 +52,7 @@ class StrategyUpdater: """ source_file = strategy_obj['location'] + print(f"started conversion of {source_file}") strategies_backup_folder = Path.joinpath(config['user_data_dir'], "strategies_orig_updater") target_file = Path.joinpath(strategies_backup_folder, strategy_obj['location_rel']) @@ -106,6 +107,8 @@ class NameUpdater(ast.NodeTransformer): # traverse the AST recursively by calling the visitor method for each child node if hasattr(node, "_fields"): for field_name, field_value in ast.iter_fields(node): + if not isinstance(field_value, ast.AST): + continue # to avoid unnecessary loops self.visit(field_value) self.generic_visit(field_value) self.check_fields(field_value) @@ -204,8 +207,9 @@ class NameUpdater(ast.NodeTransformer): node.slice.value = StrategyUpdater.rename_dict[node.slice.value] if hasattr(node.slice, "elts"): self.visit_slice_elts(node.slice.elts) - if hasattr(node.slice.value, "elts"): - self.visit_slice_elts(node.slice.value.elts) + if hasattr(node.slice, "value"): + if hasattr(node.slice.value, "elts"): + self.visit_slice_elts(node.slice.value.elts) return node # elts can have elts (technically recursively) From a51e44eea304e548c74c190aed6a6adb8f81d0ed Mon Sep 17 00:00:00 2001 From: hippocritical Date: Sun, 1 Jan 2023 12:37:15 +0100 Subject: [PATCH 004/229] Adding tests --- freqtrade/commands/strategy_utils_commands.py | 10 +++- freqtrade/strategy/strategyupdater.py | 35 +++++------- tests/test_strategy_updater.py | 56 +++++++++++++++++++ 3 files changed, 76 insertions(+), 25 deletions(-) create mode 100644 tests/test_strategy_updater.py diff --git a/freqtrade/commands/strategy_utils_commands.py b/freqtrade/commands/strategy_utils_commands.py index cf7ba5e13..1f3c27e0d 100644 --- a/freqtrade/commands/strategy_utils_commands.py +++ b/freqtrade/commands/strategy_utils_commands.py @@ -25,12 +25,16 @@ def start_strategy_update(args: Dict[str, Any]) -> None: config, enum_failed=True, recursive=config.get('recursive_strategy_search', False)) filtered_strategy_objs = [] - for strategy_obj in strategy_objs: - for args_strategy in args['strategy_list']: + for args_strategy in args['strategy_list']: + found = False + for strategy_obj in strategy_objs: if strategy_obj['name'] == args_strategy and strategy_obj not in filtered_strategy_objs: filtered_strategy_objs.append(strategy_obj) + found = True break - print(f"strategy {strategy_obj['name']} could not be loaded or found and is skipped.") + + if not found: + print(f"strategy {strategy_obj['name']} could not be loaded or found and is skipped.") for filtered_strategy_obj in filtered_strategy_objs: # Initialize backtesting object diff --git a/freqtrade/strategy/strategyupdater.py b/freqtrade/strategy/strategyupdater.py index 74bb4454c..396d57a8a 100644 --- a/freqtrade/strategy/strategyupdater.py +++ b/freqtrade/strategy/strategyupdater.py @@ -70,7 +70,6 @@ class StrategyUpdater: # update the code new_code = StrategyUpdater.update_code(self, old_code) - # write the modified code to the destination folder with open(source_file, 'w') as f: f.write(new_code) @@ -82,8 +81,7 @@ class StrategyUpdater: tree = ast.parse(code) # use the AST to update the code - updated_code = self.modify_ast( - tree) + updated_code = self.modify_ast(self, tree) # return the modified code without executing it return updated_code @@ -107,18 +105,8 @@ class NameUpdater(ast.NodeTransformer): # traverse the AST recursively by calling the visitor method for each child node if hasattr(node, "_fields"): for field_name, field_value in ast.iter_fields(node): - if not isinstance(field_value, ast.AST): - continue # to avoid unnecessary loops - self.visit(field_value) - self.generic_visit(field_value) - self.check_fields(field_value) self.check_strategy_and_config_settings(node, field_value) - # add this check to handle the case where field_value is a slice - if isinstance(field_value, ast.Slice): - self.visit(field_value) - # add this check to handle the case where field_value is a target - if isinstance(field_value, ast.expr_context): - self.visit(field_value) + self.check_fields(field_value) def check_fields(self, field_value): if isinstance(field_value, list): @@ -139,10 +127,6 @@ class NameUpdater(ast.NodeTransformer): target.id == "unfilledtimeout"): for key in field_value.keys: self.visit(key) - # Check if the target is a Subscript object with a "value" attribute - if isinstance(target, ast.Subscript) and hasattr(target.value, "attr"): - if target.value.attr == "loc": - self.visit(target) def visit_Name(self, node): # if the name is in the mapping, update it @@ -154,11 +138,14 @@ class NameUpdater(ast.NodeTransformer): # do not update the names in import statements return node + # This function is currently never successfully triggered + # since freqtrade currently only allows valid code to be processed. + # The module .hyper does not anymore exist and by that fails to even + # reach this function to be updated currently. def visit_ImportFrom(self, node): - # do not update the names in import statements - if hasattr(node, "module"): - if node.module == "freqtrade.strategy.hyper": - node.module = "freqtrade.strategy" + # if hasattr(node, "module"): + # if node.module == "freqtrade.strategy.hyper": + # node.module = "freqtrade.strategy" return node def visit_FunctionDef(self, node): @@ -210,6 +197,10 @@ class NameUpdater(ast.NodeTransformer): if hasattr(node.slice, "value"): if hasattr(node.slice.value, "elts"): self.visit_slice_elts(node.slice.value.elts) + # Check if the target is a Subscript object with a "value" attribute + # if isinstance(target, ast.Subscript) and hasattr(target.value, "attr"): + # if target.value.attr == "loc": + # self.visit(target) return node # elts can have elts (technically recursively) diff --git a/tests/test_strategy_updater.py b/tests/test_strategy_updater.py new file mode 100644 index 000000000..6997abdce --- /dev/null +++ b/tests/test_strategy_updater.py @@ -0,0 +1,56 @@ +# pragma pylint: disable=missing-docstring, protected-access, invalid-name + +from freqtrade.strategy.strategyupdater import StrategyUpdater + + +def test_strategy_updater(default_conf, caplog) -> None: + modified_code1 = StrategyUpdater.update_code(StrategyUpdater, """ +class testClass(IStrategy): + def populate_buy_trend(): + pass + def populate_sell_trend(): + pass + def check_buy_timeout(): + pass + def check_sell_timeout(): + pass + def custom_sell(): + pass +""") + + modified_code2 = StrategyUpdater.update_code(StrategyUpdater, """ +buy_some_parameter = IntParameter(space='buy') +sell_some_parameter = IntParameter(space='sell') +ticker_interval = '15m' +""") + modified_code3 = StrategyUpdater.update_code(StrategyUpdater, """ +use_sell_signal = True +sell_profit_only = True +sell_profit_offset = True +ignore_roi_if_buy_signal = True +forcebuy_enable = True +""") + modified_code4 = StrategyUpdater.update_code(StrategyUpdater, """ +dataframe.loc[reduce(lambda x, y: x & y, conditions), 'buy'] = 1 +dataframe.loc[reduce(lambda x, y: x & y, conditions), 'sell'] = 1 +""") + assert "populate_entry_trend" in modified_code1 + assert "populate_exit_trend" in modified_code1 + assert "check_entry_timeout" in modified_code1 + assert "check_exit_timeout" in modified_code1 + assert "custom_exit" in modified_code1 + assert "INTERFACE_VERSION = 3" in modified_code1 + + assert "timeframe" in modified_code2 + # check for not editing hyperopt spaces + assert "space='buy'" in modified_code2 + assert "space='sell'" in modified_code2 + + assert "use_exit_signal" in modified_code3 + assert "exit_profit_only" in modified_code3 + assert "exit_profit_offset" in modified_code3 + assert "ignore_roi_if_entry_signal" in modified_code3 + assert "force_entry_enable" in modified_code3 + + assert "enter_long" in modified_code4 + assert "exit_long" in modified_code4 From 762dd4f024907ea9f9ddd0ac303eaf9f77e6dec4 Mon Sep 17 00:00:00 2001 From: hippocritical Date: Sun, 1 Jan 2023 18:57:38 +0100 Subject: [PATCH 005/229] Adding tests added more code inside NameUpdater to grab more variables. --- freqtrade/strategy/strategyupdater.py | 40 +++++++++++++++++++++------ tests/test_strategy_updater.py | 11 +++++++- 2 files changed, 42 insertions(+), 9 deletions(-) diff --git a/freqtrade/strategy/strategyupdater.py b/freqtrade/strategy/strategyupdater.py index 396d57a8a..5b4bb8be0 100644 --- a/freqtrade/strategy/strategyupdater.py +++ b/freqtrade/strategy/strategyupdater.py @@ -128,6 +128,15 @@ class NameUpdater(ast.NodeTransformer): for key in field_value.keys: self.visit(key) + def check_args(self, node): + if isinstance(node.args, ast.arguments): + self.check_args(node.args) + if hasattr(node, "args"): + if isinstance(node.args, list): + for arg in node.args: + arg.arg = StrategyUpdater.name_mapping[arg.arg] + return node + def visit_Name(self, node): # if the name is in the mapping, update it if node.id in StrategyUpdater.name_mapping: @@ -152,6 +161,8 @@ class NameUpdater(ast.NodeTransformer): # if the function name is in the mapping, update it if node.name in StrategyUpdater.function_mapping: node.name = StrategyUpdater.function_mapping[node.name] + if hasattr(node, "args"): + self.check_args(node) return self.generic_visit(node) def visit_Attribute(self, node): @@ -193,10 +204,10 @@ class NameUpdater(ast.NodeTransformer): # Replace the slice attributes with the values from rename_dict node.slice.value = StrategyUpdater.rename_dict[node.slice.value] if hasattr(node.slice, "elts"): - self.visit_slice_elts(node.slice.elts) + self.visit_elts(node.slice.elts) if hasattr(node.slice, "value"): if hasattr(node.slice.value, "elts"): - self.visit_slice_elts(node.slice.value.elts) + self.visit_elts(node.slice.value.elts) # Check if the target is a Subscript object with a "value" attribute # if isinstance(target, ast.Subscript) and hasattr(target.value, "attr"): # if target.value.attr == "loc": @@ -204,12 +215,25 @@ class NameUpdater(ast.NodeTransformer): return node # elts can have elts (technically recursively) - def visit_slice_elts(self, elts): - for elt in elts: - if isinstance(elt, ast.Constant) and elt.value in StrategyUpdater.rename_dict: - elt.value = StrategyUpdater.rename_dict[elt.value] - elif hasattr(elt, "elts"): - self.visit_slice_elts(elt.elts) + def visit_elts(self, elts): + if isinstance(elts, list): + for elt in elts: + self.visit_elt(elt) + else: + self.visit_elt(elts) + + # sub function again needed since the structure itself is highly flexible ... + def visit_elt(self, elt): + if isinstance(elt, ast.Constant) and elt.value in StrategyUpdater.rename_dict: + elt.value = StrategyUpdater.rename_dict[elt.value] + if hasattr(elt, "elts"): + self.visit_elts(elt.elts) + if hasattr(elt, "args"): + if isinstance(elt.args, ast.arguments): + self.visit_elts(elt.args) + else: + for arg in elt.args: + self.visit_elts(arg) def visit_Constant(self, node): # do not update the names in import statements diff --git a/tests/test_strategy_updater.py b/tests/test_strategy_updater.py index 6997abdce..cf18fcc25 100644 --- a/tests/test_strategy_updater.py +++ b/tests/test_strategy_updater.py @@ -4,6 +4,11 @@ from freqtrade.strategy.strategyupdater import StrategyUpdater def test_strategy_updater(default_conf, caplog) -> None: + modified_code5 = StrategyUpdater.update_code(StrategyUpdater, """ +def confirm_trade_exit(sell_reason: str): + pass +""") + modified_code1 = StrategyUpdater.update_code(StrategyUpdater, """ class testClass(IStrategy): def populate_buy_trend(): @@ -31,9 +36,10 @@ ignore_roi_if_buy_signal = True forcebuy_enable = True """) modified_code4 = StrategyUpdater.update_code(StrategyUpdater, """ -dataframe.loc[reduce(lambda x, y: x & y, conditions), 'buy'] = 1 +dataframe.loc[reduce(lambda x, y: x & y, conditions), ["buy", "buy_tag"]] = (1, "buy_signal_1") dataframe.loc[reduce(lambda x, y: x & y, conditions), 'sell'] = 1 """) + assert "populate_entry_trend" in modified_code1 assert "populate_exit_trend" in modified_code1 assert "check_entry_timeout" in modified_code1 @@ -54,3 +60,6 @@ dataframe.loc[reduce(lambda x, y: x & y, conditions), 'sell'] = 1 assert "enter_long" in modified_code4 assert "exit_long" in modified_code4 + assert "enter_tag" in modified_code4 + + assert "exit_reason" in modified_code5 From 66f7c913570b29be29d180caa1e50ff75f2438b2 Mon Sep 17 00:00:00 2001 From: hippocritical Date: Sun, 1 Jan 2023 22:03:45 +0100 Subject: [PATCH 006/229] Adding tests added more code inside NameUpdater to grab more variables. --- freqtrade/strategy/strategyupdater.py | 18 +++++++++- requirements.txt | 20 +++++++++++ tests/test_strategy_updater.py | 50 +++++++++++++++++++++------ 3 files changed, 77 insertions(+), 11 deletions(-) diff --git a/freqtrade/strategy/strategyupdater.py b/freqtrade/strategy/strategyupdater.py index 5b4bb8be0..1a0423076 100644 --- a/freqtrade/strategy/strategyupdater.py +++ b/freqtrade/strategy/strategyupdater.py @@ -107,12 +107,16 @@ class NameUpdater(ast.NodeTransformer): for field_name, field_value in ast.iter_fields(node): self.check_strategy_and_config_settings(node, field_value) self.check_fields(field_value) + for child in ast.iter_child_nodes(node): + self.generic_visit(child) def check_fields(self, field_value): if isinstance(field_value, list): for item in field_value: - if isinstance(item, ast.AST): + if isinstance(item, ast.AST) or isinstance(item, ast.If): self.visit(item) + if isinstance(field_value, ast.Name): + self.visit_Name(field_value) def check_strategy_and_config_settings(self, node, field_value): if (isinstance(field_value, ast.AST) and @@ -157,6 +161,11 @@ class NameUpdater(ast.NodeTransformer): # node.module = "freqtrade.strategy" return node + def visit_If(self, node: ast.If): + for child in ast.iter_child_nodes(node): + self.visit(child) + return self.generic_visit(node) + def visit_FunctionDef(self, node): # if the function name is in the mapping, update it if node.name in StrategyUpdater.function_mapping: @@ -165,6 +174,13 @@ class NameUpdater(ast.NodeTransformer): self.check_args(node) return self.generic_visit(node) + def visit_Assign(self, node): + if hasattr(node, "targets") and isinstance(node.targets, list): + for target in node.targets: + if hasattr(target, "id") and target.id in StrategyUpdater.name_mapping: + target.id = StrategyUpdater.name_mapping[target.id] + return node + def visit_Attribute(self, node): # if the attribute name is 'nr_of_successful_buys', # update it to 'nr_of_successful_entries' diff --git a/requirements.txt b/requirements.txt index 90bc4f702..3229ec3c4 100644 --- a/requirements.txt +++ b/requirements.txt @@ -57,3 +57,23 @@ schedule==1.1.0 #WS Messages websockets==10.4 janus==1.0.0 + +pytest~=7.2.0 +freqtrade~=2022.12.dev0 +filelock~=3.8.2 +plotly~=5.11.0 +setuptools~=65.6.3 +starlette~=0.22.0 +gym~=0.21.0 +torch~=1.13.1 +scikit-learn~=1.1.3 +scipy~=1.9.3 +xgboost~=1.7.2 +catboost~=1.1.1 +lightgbm~=3.3.3 +astor~=0.8.1 +ta~=0.10.2 +finta~=1.3 +tapy~=1.9.1 +matplotlib~=3.6.2 +PyYAML~=6.0 diff --git a/tests/test_strategy_updater.py b/tests/test_strategy_updater.py index cf18fcc25..5736e5c76 100644 --- a/tests/test_strategy_updater.py +++ b/tests/test_strategy_updater.py @@ -4,11 +4,11 @@ from freqtrade.strategy.strategyupdater import StrategyUpdater def test_strategy_updater(default_conf, caplog) -> None: - modified_code5 = StrategyUpdater.update_code(StrategyUpdater, """ -def confirm_trade_exit(sell_reason: str): - pass + modified_code2 = StrategyUpdater.update_code(StrategyUpdater, """ +ticker_interval = '15m' +buy_some_parameter = IntParameter(space='buy') +sell_some_parameter = IntParameter(space='sell') """) - modified_code1 = StrategyUpdater.update_code(StrategyUpdater, """ class testClass(IStrategy): def populate_buy_trend(): @@ -21,12 +21,6 @@ class testClass(IStrategy): pass def custom_sell(): pass -""") - - modified_code2 = StrategyUpdater.update_code(StrategyUpdater, """ -buy_some_parameter = IntParameter(space='buy') -sell_some_parameter = IntParameter(space='sell') -ticker_interval = '15m' """) modified_code3 = StrategyUpdater.update_code(StrategyUpdater, """ use_sell_signal = True @@ -38,6 +32,32 @@ forcebuy_enable = True modified_code4 = StrategyUpdater.update_code(StrategyUpdater, """ dataframe.loc[reduce(lambda x, y: x & y, conditions), ["buy", "buy_tag"]] = (1, "buy_signal_1") dataframe.loc[reduce(lambda x, y: x & y, conditions), 'sell'] = 1 +""") + modified_code5 = StrategyUpdater.update_code(StrategyUpdater, """ +def confirm_trade_exit(sell_reason: str): + pass + """) + modified_code6 = StrategyUpdater.update_code(StrategyUpdater, """ +order_time_in_force = { + 'buy': 'gtc', + 'sell': 'ioc' +} +order_types = { + 'buy': 'limit', + 'sell': 'market', + 'stoploss': 'market', + 'stoploss_on_exchange': False +} +unfilledtimeout = { + 'buy': 1, + 'sell': 2 +} +""") + + modified_code7 = StrategyUpdater.update_code(StrategyUpdater, """ +def confirm_trade_exit(sell_reason): + if (sell_reason == 'stop_loss'): + pass """) assert "populate_entry_trend" in modified_code1 @@ -63,3 +83,13 @@ dataframe.loc[reduce(lambda x, y: x & y, conditions), 'sell'] = 1 assert "enter_tag" in modified_code4 assert "exit_reason" in modified_code5 + + assert "'entry': 'gtc'" in modified_code6 + assert "'exit': 'ioc'" in modified_code6 + assert "'entry': 'limit'" in modified_code6 + assert "'exit': 'market'" in modified_code6 + assert "'entry': 1" in modified_code6 + assert "'exit': 2" in modified_code6 + + assert "exit_reason" in modified_code7 + assert "exit_reason == 'stop_loss'" in modified_code7 From e89609dc3a9fc32003243785c9a2e173a4ebd09d Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 2 Jan 2023 08:51:54 +0100 Subject: [PATCH 007/229] Fix crash due to invalid parameter --- freqtrade/strategy/strategyupdater.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/freqtrade/strategy/strategyupdater.py b/freqtrade/strategy/strategyupdater.py index 1a0423076..ab757e0a9 100644 --- a/freqtrade/strategy/strategyupdater.py +++ b/freqtrade/strategy/strategyupdater.py @@ -81,7 +81,7 @@ class StrategyUpdater: tree = ast.parse(code) # use the AST to update the code - updated_code = self.modify_ast(self, tree) + updated_code = self.modify_ast(tree) # return the modified code without executing it return updated_code From a712c5d42c567751be0949a2202f48d138547c25 Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 2 Jan 2023 08:44:00 +0100 Subject: [PATCH 008/229] Improve if formatting --- freqtrade/strategy/strategyupdater.py | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/freqtrade/strategy/strategyupdater.py b/freqtrade/strategy/strategyupdater.py index ab757e0a9..a0547932c 100644 --- a/freqtrade/strategy/strategyupdater.py +++ b/freqtrade/strategy/strategyupdater.py @@ -184,9 +184,11 @@ class NameUpdater(ast.NodeTransformer): def visit_Attribute(self, node): # if the attribute name is 'nr_of_successful_buys', # update it to 'nr_of_successful_entries' - if isinstance(node.value, ast.Name) and \ - node.value.id == 'trades' and \ - node.attr == 'nr_of_successful_buys': + if ( + isinstance(node.value, ast.Name) + and node.value.id == 'trades' + and node.attr == 'nr_of_successful_buys' + ): node.attr = 'nr_of_successful_entries' return self.generic_visit(node) @@ -208,9 +210,11 @@ class NameUpdater(ast.NodeTransformer): # otherwise, update its value to 3 else: for child in node.body: - if isinstance(child, ast.Assign) and \ - isinstance(child.targets[0], ast.Name) and \ - child.targets[0].id == 'INTERFACE_VERSION': + if ( + isinstance(child, ast.Assign) + and isinstance(child.targets[0], ast.Name) + and child.targets[0].id == 'INTERFACE_VERSION' + ): child.value = ast.parse('3').body[0].value return self.generic_visit(node) @@ -253,8 +257,6 @@ class NameUpdater(ast.NodeTransformer): def visit_Constant(self, node): # do not update the names in import statements - if node.value in \ - StrategyUpdater.otif_ot_unfilledtimeout: - node.value = \ - StrategyUpdater.otif_ot_unfilledtimeout[node.value] + if node.value in StrategyUpdater.otif_ot_unfilledtimeout: + node.value = StrategyUpdater.otif_ot_unfilledtimeout[node.value] return node From df25dbc048594870d6e5c9356575b47326d8ddef Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 2 Jan 2023 08:52:18 +0100 Subject: [PATCH 009/229] Don't require a configuration for strategy-updater --- freqtrade/commands/arguments.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/freqtrade/commands/arguments.py b/freqtrade/commands/arguments.py index 9990ad230..a3cdc378a 100644 --- a/freqtrade/commands/arguments.py +++ b/freqtrade/commands/arguments.py @@ -111,7 +111,8 @@ ARGS_ANALYZE_ENTRIES_EXITS = ["exportfilename", "analysis_groups", "enter_reason NO_CONF_REQURIED = ["convert-data", "convert-trade-data", "download-data", "list-timeframes", "list-markets", "list-pairs", "list-strategies", "list-freqaimodels", "list-data", "hyperopt-list", "hyperopt-show", "backtest-filter", - "plot-dataframe", "plot-profit", "show-trades", "trades-to-ohlcv"] + "plot-dataframe", "plot-profit", "show-trades", "trades-to-ohlcv", + "strategy-updater"] NO_CONF_ALLOWED = ["create-userdir", "list-exchanges", "new-strategy"] From 61d7129d7ce65edcbbdd75f7047d47ad75051cce Mon Sep 17 00:00:00 2001 From: hippocritical <41228167+hippocritical@users.noreply.github.com> Date: Mon, 2 Jan 2023 16:51:05 +0100 Subject: [PATCH 010/229] Update freqtrade/commands/strategy_utils_commands.py Co-authored-by: Matthias --- freqtrade/commands/strategy_utils_commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/freqtrade/commands/strategy_utils_commands.py b/freqtrade/commands/strategy_utils_commands.py index 1f3c27e0d..0325f411c 100644 --- a/freqtrade/commands/strategy_utils_commands.py +++ b/freqtrade/commands/strategy_utils_commands.py @@ -39,4 +39,4 @@ def start_strategy_update(args: Dict[str, Any]) -> None: for filtered_strategy_obj in filtered_strategy_objs: # Initialize backtesting object instance_strategy_updater = StrategyUpdater() - StrategyUpdater.start(instance_strategy_updater, config, filtered_strategy_obj) + self.start(config, filtered_strategy_obj) From 0817e1698f654a13fd6f01c2519dee5f1cc19f99 Mon Sep 17 00:00:00 2001 From: hippocritical Date: Mon, 2 Jan 2023 20:45:56 +0100 Subject: [PATCH 011/229] requirements thinned out again StrategyResolver.search_all_objects(enum_failed) set to False since we got no use in True shortened update_code call added modified_code8 test which currently still fails. (and thereby is commented out) --- freqtrade/commands/strategy_utils_commands.py | 2 +- freqtrade/strategy/strategyupdater.py | 8 +++++--- requirements.txt | 18 ------------------ tests/test_strategy_updater.py | 11 +++++++++++ 4 files changed, 17 insertions(+), 22 deletions(-) diff --git a/freqtrade/commands/strategy_utils_commands.py b/freqtrade/commands/strategy_utils_commands.py index 1f3c27e0d..5d8ede9a2 100644 --- a/freqtrade/commands/strategy_utils_commands.py +++ b/freqtrade/commands/strategy_utils_commands.py @@ -22,7 +22,7 @@ def start_strategy_update(args: Dict[str, Any]) -> None: config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE) strategy_objs = StrategyResolver.search_all_objects( - config, enum_failed=True, recursive=config.get('recursive_strategy_search', False)) + config, enum_failed=False, recursive=config.get('recursive_strategy_search', False)) filtered_strategy_objs = [] for args_strategy in args['strategy_list']: diff --git a/freqtrade/strategy/strategyupdater.py b/freqtrade/strategy/strategyupdater.py index 1a0423076..7f3a1feff 100644 --- a/freqtrade/strategy/strategyupdater.py +++ b/freqtrade/strategy/strategyupdater.py @@ -69,7 +69,7 @@ class StrategyUpdater: shutil.copy(source_file, target_file) # update the code - new_code = StrategyUpdater.update_code(self, old_code) + new_code = self.update_code(old_code) # write the modified code to the destination folder with open(source_file, 'w') as f: f.write(new_code) @@ -113,7 +113,8 @@ class NameUpdater(ast.NodeTransformer): def check_fields(self, field_value): if isinstance(field_value, list): for item in field_value: - if isinstance(item, ast.AST) or isinstance(item, ast.If): + if (isinstance(item, ast.AST) or isinstance(item, ast.If) or + isinstance(item, ast.Expr)): self.visit(item) if isinstance(field_value, ast.Name): self.visit_Name(field_value) @@ -138,7 +139,8 @@ class NameUpdater(ast.NodeTransformer): if hasattr(node, "args"): if isinstance(node.args, list): for arg in node.args: - arg.arg = StrategyUpdater.name_mapping[arg.arg] + if arg.arg in StrategyUpdater.name_mapping: + arg.arg = StrategyUpdater.name_mapping[arg.arg] return node def visit_Name(self, node): diff --git a/requirements.txt b/requirements.txt index 3229ec3c4..da1db316b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -58,22 +58,4 @@ schedule==1.1.0 websockets==10.4 janus==1.0.0 -pytest~=7.2.0 -freqtrade~=2022.12.dev0 -filelock~=3.8.2 -plotly~=5.11.0 -setuptools~=65.6.3 -starlette~=0.22.0 -gym~=0.21.0 -torch~=1.13.1 -scikit-learn~=1.1.3 -scipy~=1.9.3 -xgboost~=1.7.2 -catboost~=1.1.1 -lightgbm~=3.3.3 astor~=0.8.1 -ta~=0.10.2 -finta~=1.3 -tapy~=1.9.1 -matplotlib~=3.6.2 -PyYAML~=6.0 diff --git a/tests/test_strategy_updater.py b/tests/test_strategy_updater.py index 5736e5c76..682c715fe 100644 --- a/tests/test_strategy_updater.py +++ b/tests/test_strategy_updater.py @@ -59,6 +59,11 @@ def confirm_trade_exit(sell_reason): if (sell_reason == 'stop_loss'): pass """) + # modified_code8 = StrategyUpdater.update_code(StrategyUpdater, """ + # sell_reason == 'sell_signal' + # sell_reason == 'force_sell' + # sell_reason == 'emergency_sell' + # """) assert "populate_entry_trend" in modified_code1 assert "populate_exit_trend" in modified_code1 @@ -93,3 +98,9 @@ def confirm_trade_exit(sell_reason): assert "exit_reason" in modified_code7 assert "exit_reason == 'stop_loss'" in modified_code7 + + # those tests currently don't work, next in line. + # assert "exit_signal" in modified_code8 + # assert "exit_reason" in modified_code8 + # assert "force_exit" in modified_code8 + # assert "emergency_exit" in modified_code8 From 71ec32ac9e8360a87b9aeec32327f2824af24f0f Mon Sep 17 00:00:00 2001 From: hippocritical Date: Mon, 2 Jan 2023 23:35:51 +0100 Subject: [PATCH 012/229] removed prints for strategy could not be loaded changed back to ast, astor is not really needed. --- freqtrade/commands/strategy_utils_commands.py | 8 +------- freqtrade/strategy/strategyupdater.py | 18 ++++++++---------- 2 files changed, 9 insertions(+), 17 deletions(-) diff --git a/freqtrade/commands/strategy_utils_commands.py b/freqtrade/commands/strategy_utils_commands.py index 5aeac2266..4a7eacda0 100644 --- a/freqtrade/commands/strategy_utils_commands.py +++ b/freqtrade/commands/strategy_utils_commands.py @@ -26,17 +26,11 @@ def start_strategy_update(args: Dict[str, Any]) -> None: filtered_strategy_objs = [] for args_strategy in args['strategy_list']: - found = False for strategy_obj in strategy_objs: if strategy_obj['name'] == args_strategy and strategy_obj not in filtered_strategy_objs: filtered_strategy_objs.append(strategy_obj) - found = True break - if not found: - print(f"strategy {strategy_obj['name']} could not be loaded or found and is skipped.") - for filtered_strategy_obj in filtered_strategy_objs: - # Initialize backtesting object instance_strategy_updater = StrategyUpdater() - self.start(config, filtered_strategy_obj) + instance_strategy_updater.start(config, filtered_strategy_obj) diff --git a/freqtrade/strategy/strategyupdater.py b/freqtrade/strategy/strategyupdater.py index 8a55de1b6..d12d3eaaa 100644 --- a/freqtrade/strategy/strategyupdater.py +++ b/freqtrade/strategy/strategyupdater.py @@ -3,8 +3,6 @@ import os import shutil from pathlib import Path -import astor - class StrategyUpdater: name_mapping = { @@ -59,7 +57,7 @@ class StrategyUpdater: # read the file with open(source_file, 'r') as f: old_code = f.read() - if not os.path.exists(strategies_backup_folder): + if not strategies_backup_folder.is_dir(): os.makedirs(strategies_backup_folder) # backup original @@ -96,7 +94,7 @@ class StrategyUpdater: ast.increment_lineno(tree, n=1) # generate the new code from the updated AST - return astor.to_source(tree) + return ast.dump(tree) # Here we go through each respective node, slice, elt, key ... to replace outdated entries. @@ -187,9 +185,9 @@ class NameUpdater(ast.NodeTransformer): # if the attribute name is 'nr_of_successful_buys', # update it to 'nr_of_successful_entries' if ( - isinstance(node.value, ast.Name) - and node.value.id == 'trades' - and node.attr == 'nr_of_successful_buys' + isinstance(node.value, ast.Name) + and node.value.id == 'trades' + and node.attr == 'nr_of_successful_buys' ): node.attr = 'nr_of_successful_entries' return self.generic_visit(node) @@ -213,9 +211,9 @@ class NameUpdater(ast.NodeTransformer): else: for child in node.body: if ( - isinstance(child, ast.Assign) - and isinstance(child.targets[0], ast.Name) - and child.targets[0].id == 'INTERFACE_VERSION' + isinstance(child, ast.Assign) + and isinstance(child.targets[0], ast.Name) + and child.targets[0].id == 'INTERFACE_VERSION' ): child.value = ast.parse('3').body[0].value return self.generic_visit(node) From ed55296d202d725b5d2d5e95e60273a8d21dcf1a Mon Sep 17 00:00:00 2001 From: hippocritical Date: Wed, 4 Jan 2023 23:49:33 +0100 Subject: [PATCH 013/229] removed prints for strategy could not be loaded Changed logic to contain much less if conditions currently still missing: Webhook terminology, Telegram notification settings, Strategy/Config settings --- freqtrade/strategy/strategyupdater.py | 124 ++++++++++++-------------- tests/test_strategy_updater.py | 31 ++++--- 2 files changed, 73 insertions(+), 82 deletions(-) diff --git a/freqtrade/strategy/strategyupdater.py b/freqtrade/strategy/strategyupdater.py index d12d3eaaa..ad14bb903 100644 --- a/freqtrade/strategy/strategyupdater.py +++ b/freqtrade/strategy/strategyupdater.py @@ -3,6 +3,8 @@ import os import shutil from pathlib import Path +import astor + class StrategyUpdater: name_mapping = { @@ -79,7 +81,7 @@ class StrategyUpdater: tree = ast.parse(code) # use the AST to update the code - updated_code = self.modify_ast(tree) + updated_code = self.modify_ast(self, tree) # return the modified code without executing it return updated_code @@ -94,67 +96,67 @@ class StrategyUpdater: ast.increment_lineno(tree, n=1) # generate the new code from the updated AST - return ast.dump(tree) + return astor.to_source(tree) # Here we go through each respective node, slice, elt, key ... to replace outdated entries. class NameUpdater(ast.NodeTransformer): def generic_visit(self, node): - # traverse the AST recursively by calling the visitor method for each child node - if hasattr(node, "_fields"): - for field_name, field_value in ast.iter_fields(node): - self.check_strategy_and_config_settings(node, field_value) - self.check_fields(field_value) - for child in ast.iter_child_nodes(node): - self.generic_visit(child) - def check_fields(self, field_value): - if isinstance(field_value, list): - for item in field_value: - if (isinstance(item, ast.AST) or isinstance(item, ast.If) or - isinstance(item, ast.Expr)): - self.visit(item) - if isinstance(field_value, ast.Name): - self.visit_Name(field_value) + # space is not yet transferred from buy/sell to entry/exit and thereby has to be skipped. + if isinstance(node, ast.keyword): + if node.arg == "space": + return node - def check_strategy_and_config_settings(self, node, field_value): - if (isinstance(field_value, ast.AST) and - hasattr(node, "targets") and - isinstance(node.targets, list)): - for target in node.targets: - if (hasattr(target, "id") and - hasattr(field_value, "keys") and - isinstance(field_value.keys, list)): - if (target.id == "order_time_in_force" or - target.id == "order_types" or - target.id == "unfilledtimeout"): - for key in field_value.keys: - self.visit(key) + # from here on this is the original function. + for field, old_value in ast.iter_fields(node): + if isinstance(old_value, list): + new_values = [] + for value in old_value: + if isinstance(value, ast.AST): + value = self.visit(value) + if value is None: + continue + elif not isinstance(value, ast.AST): + new_values.extend(value) + continue + new_values.append(value) + old_value[:] = new_values + elif isinstance(old_value, ast.AST): + new_node = self.visit(old_value) + if new_node is None: + delattr(node, field) + else: + setattr(node, field, new_node) + return node - def check_args(self, node): - if isinstance(node.args, ast.arguments): - self.check_args(node.args) - if hasattr(node, "args"): - if isinstance(node.args, list): - for arg in node.args: - if arg.arg in StrategyUpdater.name_mapping: - arg.arg = StrategyUpdater.name_mapping[arg.arg] + def visit_Expr(self, node): + node.value.left.id = self.check_dict(StrategyUpdater.name_mapping, node.value.left.id) + self.visit(node.value) + return node + + # Renames an element if contained inside a dictionary. + @staticmethod + def check_dict(current_dict: dict, element: str): + if element in current_dict: + element = current_dict[element] + return element + + def visit_arguments(self, node): + if isinstance(node.args, list): + for arg in node.args: + arg.arg = self.check_dict(StrategyUpdater.name_mapping, arg.arg) return node def visit_Name(self, node): # if the name is in the mapping, update it - if node.id in StrategyUpdater.name_mapping: - node.id = StrategyUpdater.name_mapping[node.id] + node.id = self.check_dict(StrategyUpdater.name_mapping, node.id) return node def visit_Import(self, node): # do not update the names in import statements return node - # This function is currently never successfully triggered - # since freqtrade currently only allows valid code to be processed. - # The module .hyper does not anymore exist and by that fails to even - # reach this function to be updated currently. def visit_ImportFrom(self, node): # if hasattr(node, "module"): # if node.module == "freqtrade.strategy.hyper": @@ -164,33 +166,21 @@ class NameUpdater(ast.NodeTransformer): def visit_If(self, node: ast.If): for child in ast.iter_child_nodes(node): self.visit(child) - return self.generic_visit(node) + return node def visit_FunctionDef(self, node): - # if the function name is in the mapping, update it - if node.name in StrategyUpdater.function_mapping: - node.name = StrategyUpdater.function_mapping[node.name] - if hasattr(node, "args"): - self.check_args(node) - return self.generic_visit(node) - - def visit_Assign(self, node): - if hasattr(node, "targets") and isinstance(node.targets, list): - for target in node.targets: - if hasattr(target, "id") and target.id in StrategyUpdater.name_mapping: - target.id = StrategyUpdater.name_mapping[target.id] + node.name = self.check_dict(StrategyUpdater.function_mapping, node.name) + self.generic_visit(node) return node def visit_Attribute(self, node): - # if the attribute name is 'nr_of_successful_buys', - # update it to 'nr_of_successful_entries' if ( isinstance(node.value, ast.Name) and node.value.id == 'trades' and node.attr == 'nr_of_successful_buys' ): node.attr = 'nr_of_successful_entries' - return self.generic_visit(node) + return node def visit_ClassDef(self, node): # check if the class is derived from IStrategy @@ -216,7 +206,8 @@ class NameUpdater(ast.NodeTransformer): and child.targets[0].id == 'INTERFACE_VERSION' ): child.value = ast.parse('3').body[0].value - return self.generic_visit(node) + self.generic_visit(node) + return node def visit_Subscript(self, node): if isinstance(node.slice, ast.Constant): @@ -228,10 +219,6 @@ class NameUpdater(ast.NodeTransformer): if hasattr(node.slice, "value"): if hasattr(node.slice.value, "elts"): self.visit_elts(node.slice.value.elts) - # Check if the target is a Subscript object with a "value" attribute - # if isinstance(target, ast.Subscript) and hasattr(target.value, "attr"): - # if target.value.attr == "loc": - # self.visit(target) return node # elts can have elts (technically recursively) @@ -241,6 +228,7 @@ class NameUpdater(ast.NodeTransformer): self.visit_elt(elt) else: self.visit_elt(elts) + return elts # sub function again needed since the structure itself is highly flexible ... def visit_elt(self, elt): @@ -254,9 +242,9 @@ class NameUpdater(ast.NodeTransformer): else: for arg in elt.args: self.visit_elts(arg) + return elt def visit_Constant(self, node): - # do not update the names in import statements - if node.value in StrategyUpdater.otif_ot_unfilledtimeout: - node.value = StrategyUpdater.otif_ot_unfilledtimeout[node.value] + node.value = self.check_dict(StrategyUpdater.otif_ot_unfilledtimeout, node.value) + node.value = self.check_dict(StrategyUpdater.name_mapping, node.value) return node diff --git a/tests/test_strategy_updater.py b/tests/test_strategy_updater.py index 682c715fe..3ece2b3d8 100644 --- a/tests/test_strategy_updater.py +++ b/tests/test_strategy_updater.py @@ -4,11 +4,6 @@ from freqtrade.strategy.strategyupdater import StrategyUpdater def test_strategy_updater(default_conf, caplog) -> None: - modified_code2 = StrategyUpdater.update_code(StrategyUpdater, """ -ticker_interval = '15m' -buy_some_parameter = IntParameter(space='buy') -sell_some_parameter = IntParameter(space='sell') -""") modified_code1 = StrategyUpdater.update_code(StrategyUpdater, """ class testClass(IStrategy): def populate_buy_trend(): @@ -21,6 +16,11 @@ class testClass(IStrategy): pass def custom_sell(): pass +""") + modified_code2 = StrategyUpdater.update_code(StrategyUpdater, """ +ticker_interval = '15m' +buy_some_parameter = IntParameter(space='buy') +sell_some_parameter = IntParameter(space='sell') """) modified_code3 = StrategyUpdater.update_code(StrategyUpdater, """ use_sell_signal = True @@ -59,11 +59,14 @@ def confirm_trade_exit(sell_reason): if (sell_reason == 'stop_loss'): pass """) - # modified_code8 = StrategyUpdater.update_code(StrategyUpdater, """ - # sell_reason == 'sell_signal' - # sell_reason == 'force_sell' - # sell_reason == 'emergency_sell' - # """) + modified_code8 = StrategyUpdater.update_code(StrategyUpdater, """ +sell_reason == 'sell_signal' +sell_reason == 'force_sell' +sell_reason == 'emergency_sell' +""") + + # currently still missing: + # Webhook terminology, Telegram notification settings, Strategy/Config settings assert "populate_entry_trend" in modified_code1 assert "populate_exit_trend" in modified_code1 @@ -100,7 +103,7 @@ def confirm_trade_exit(sell_reason): assert "exit_reason == 'stop_loss'" in modified_code7 # those tests currently don't work, next in line. - # assert "exit_signal" in modified_code8 - # assert "exit_reason" in modified_code8 - # assert "force_exit" in modified_code8 - # assert "emergency_exit" in modified_code8 + assert "exit_signal" in modified_code8 + assert "exit_reason" in modified_code8 + assert "force_exit" in modified_code8 + assert "emergency_exit" in modified_code8 From 4435c4fd0d1de2e6b57375051d8007ca7435c5ac Mon Sep 17 00:00:00 2001 From: hippocritical Date: Thu, 5 Jan 2023 22:56:06 +0100 Subject: [PATCH 014/229] removed prints for strategy could not be loaded Changed logic to contain much less if conditions currently still missing: Webhook terminology, Telegram notification settings, Strategy/Config settings --- freqtrade/commands/strategy_utils_commands.py | 4 ++++ freqtrade/strategy/strategyupdater.py | 10 +++++----- tests/test_strategy_updater.py | 17 +++++++++-------- 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/freqtrade/commands/strategy_utils_commands.py b/freqtrade/commands/strategy_utils_commands.py index 4a7eacda0..75b8a9cc0 100644 --- a/freqtrade/commands/strategy_utils_commands.py +++ b/freqtrade/commands/strategy_utils_commands.py @@ -1,4 +1,5 @@ import logging +import time from typing import Any, Dict from freqtrade.configuration import setup_utils_configuration @@ -33,4 +34,7 @@ def start_strategy_update(args: Dict[str, Any]) -> None: for filtered_strategy_obj in filtered_strategy_objs: instance_strategy_updater = StrategyUpdater() + start = time.perf_counter() instance_strategy_updater.start(config, filtered_strategy_obj) + elapsed = time.perf_counter() - start + print(f"Conversion of {filtered_strategy_obj['name']} took {elapsed:.1f} seconds.") diff --git a/freqtrade/strategy/strategyupdater.py b/freqtrade/strategy/strategyupdater.py index ad14bb903..e26dd5e79 100644 --- a/freqtrade/strategy/strategyupdater.py +++ b/freqtrade/strategy/strategyupdater.py @@ -52,7 +52,6 @@ class StrategyUpdater: """ source_file = strategy_obj['location'] - print(f"started conversion of {source_file}") strategies_backup_folder = Path.joinpath(config['user_data_dir'], "strategies_orig_updater") target_file = Path.joinpath(strategies_backup_folder, strategy_obj['location_rel']) @@ -73,7 +72,6 @@ class StrategyUpdater: # write the modified code to the destination folder with open(source_file, 'w') as f: f.write(new_code) - print(f"conversion of file {source_file} successful.") # define the function to update the code def update_code(self, code): @@ -81,7 +79,7 @@ class StrategyUpdater: tree = ast.parse(code) # use the AST to update the code - updated_code = self.modify_ast(self, tree) + updated_code = self.modify_ast(tree) # return the modified code without executing it return updated_code @@ -96,6 +94,7 @@ class StrategyUpdater: ast.increment_lineno(tree, n=1) # generate the new code from the updated AST + # without indent {} parameters would just be written straight one after the other. return astor.to_source(tree) @@ -131,8 +130,9 @@ class NameUpdater(ast.NodeTransformer): return node def visit_Expr(self, node): - node.value.left.id = self.check_dict(StrategyUpdater.name_mapping, node.value.left.id) - self.visit(node.value) + if hasattr(node.value, "left") and hasattr(node.value.left, "id"): + node.value.left.id = self.check_dict(StrategyUpdater.name_mapping, node.value.left.id) + self.visit(node.value) return node # Renames an element if contained inside a dictionary. diff --git a/tests/test_strategy_updater.py b/tests/test_strategy_updater.py index 3ece2b3d8..a00340427 100644 --- a/tests/test_strategy_updater.py +++ b/tests/test_strategy_updater.py @@ -4,7 +4,8 @@ from freqtrade.strategy.strategyupdater import StrategyUpdater def test_strategy_updater(default_conf, caplog) -> None: - modified_code1 = StrategyUpdater.update_code(StrategyUpdater, """ + instance_strategy_updater = StrategyUpdater() + modified_code1 = instance_strategy_updater.update_code(""" class testClass(IStrategy): def populate_buy_trend(): pass @@ -17,27 +18,27 @@ class testClass(IStrategy): def custom_sell(): pass """) - modified_code2 = StrategyUpdater.update_code(StrategyUpdater, """ + modified_code2 = instance_strategy_updater.update_code(""" ticker_interval = '15m' buy_some_parameter = IntParameter(space='buy') sell_some_parameter = IntParameter(space='sell') """) - modified_code3 = StrategyUpdater.update_code(StrategyUpdater, """ + modified_code3 = instance_strategy_updater.update_code(""" use_sell_signal = True sell_profit_only = True sell_profit_offset = True ignore_roi_if_buy_signal = True forcebuy_enable = True """) - modified_code4 = StrategyUpdater.update_code(StrategyUpdater, """ + modified_code4 = instance_strategy_updater.update_code(""" dataframe.loc[reduce(lambda x, y: x & y, conditions), ["buy", "buy_tag"]] = (1, "buy_signal_1") dataframe.loc[reduce(lambda x, y: x & y, conditions), 'sell'] = 1 """) - modified_code5 = StrategyUpdater.update_code(StrategyUpdater, """ + modified_code5 = instance_strategy_updater.update_code(""" def confirm_trade_exit(sell_reason: str): pass """) - modified_code6 = StrategyUpdater.update_code(StrategyUpdater, """ + modified_code6 = instance_strategy_updater.update_code(""" order_time_in_force = { 'buy': 'gtc', 'sell': 'ioc' @@ -54,12 +55,12 @@ unfilledtimeout = { } """) - modified_code7 = StrategyUpdater.update_code(StrategyUpdater, """ + modified_code7 = instance_strategy_updater.update_code(""" def confirm_trade_exit(sell_reason): if (sell_reason == 'stop_loss'): pass """) - modified_code8 = StrategyUpdater.update_code(StrategyUpdater, """ + modified_code8 = instance_strategy_updater.update_code(""" sell_reason == 'sell_signal' sell_reason == 'force_sell' sell_reason == 'emergency_sell' From 06edc5c04491b15b2b43c0b9f0900cbf91958e8d Mon Sep 17 00:00:00 2001 From: hippocritical Date: Fri, 17 Feb 2023 21:01:09 +0100 Subject: [PATCH 015/229] changed to ast_comments, added tests for comments. --- freqtrade/commands/strategy_utils_commands.py | 43 ++++++++++----- freqtrade/strategy/strategyupdater.py | 54 ++++++++++--------- tests/test_strategy_updater.py | 20 +++++++ 3 files changed, 78 insertions(+), 39 deletions(-) diff --git a/freqtrade/commands/strategy_utils_commands.py b/freqtrade/commands/strategy_utils_commands.py index 75b8a9cc0..dc94f2b67 100644 --- a/freqtrade/commands/strategy_utils_commands.py +++ b/freqtrade/commands/strategy_utils_commands.py @@ -1,10 +1,12 @@ import logging +import os import time from typing import Any, Dict from freqtrade.configuration import setup_utils_configuration from freqtrade.enums import RunMode from freqtrade.resolvers import StrategyResolver +from freqtrade.strategy.strategyupdater import StrategyUpdater logger = logging.getLogger(__name__) @@ -17,24 +19,37 @@ def start_strategy_update(args: Dict[str, Any]) -> None: :return: None """ - # Import here to avoid loading backtesting module when it's not used - from freqtrade.strategy.strategyupdater import StrategyUpdater - config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE) strategy_objs = StrategyResolver.search_all_objects( config, enum_failed=False, recursive=config.get('recursive_strategy_search', False)) filtered_strategy_objs = [] - for args_strategy in args['strategy_list']: - for strategy_obj in strategy_objs: - if strategy_obj['name'] == args_strategy and strategy_obj not in filtered_strategy_objs: - filtered_strategy_objs.append(strategy_obj) - break + if hasattr(args, "strategy_list"): + for args_strategy in args['strategy_list']: + for strategy_obj in strategy_objs: + if (strategy_obj['name'] == args_strategy + and strategy_obj not in filtered_strategy_objs): + filtered_strategy_objs.append(strategy_obj) + break - for filtered_strategy_obj in filtered_strategy_objs: - instance_strategy_updater = StrategyUpdater() - start = time.perf_counter() - instance_strategy_updater.start(config, filtered_strategy_obj) - elapsed = time.perf_counter() - start - print(f"Conversion of {filtered_strategy_obj['name']} took {elapsed:.1f} seconds.") + for filtered_strategy_obj in filtered_strategy_objs: + start_conversion(filtered_strategy_obj, config) + else: + processed_locations = set() + for strategy_obj in strategy_objs: + if strategy_obj['location'] not in processed_locations: + processed_locations.add(strategy_obj['location']) + start_conversion(strategy_obj, config) + + +def start_conversion(strategy_obj, config): + # try: + print(f"Conversion of {os.path.basename(strategy_obj['location'])} started.") + instance_strategy_updater = StrategyUpdater() + start = time.perf_counter() + instance_strategy_updater.start(config, strategy_obj) + elapsed = time.perf_counter() - start + print(f"Conversion of {os.path.basename(strategy_obj['location'])} took {elapsed:.1f} seconds.") + # except: + # pass diff --git a/freqtrade/strategy/strategyupdater.py b/freqtrade/strategy/strategyupdater.py index e26dd5e79..db19d4fba 100644 --- a/freqtrade/strategy/strategyupdater.py +++ b/freqtrade/strategy/strategyupdater.py @@ -1,9 +1,8 @@ -import ast import os import shutil from pathlib import Path -import astor +import ast_comments class StrategyUpdater: @@ -76,7 +75,7 @@ class StrategyUpdater: # define the function to update the code def update_code(self, code): # parse the code into an AST - tree = ast.parse(code) + tree = ast_comments.parse(code) # use the AST to update the code updated_code = self.modify_ast(tree) @@ -90,38 +89,43 @@ class StrategyUpdater: NameUpdater().visit(tree) # first fix the comments, so it understands "\n" properly inside multi line comments. - ast.fix_missing_locations(tree) - ast.increment_lineno(tree, n=1) + ast_comments.fix_missing_locations(tree) + ast_comments.increment_lineno(tree, n=1) # generate the new code from the updated AST # without indent {} parameters would just be written straight one after the other. - return astor.to_source(tree) + + # ast_comments would be amazing since this is the only solution that carries over comments, + # but it does currently not have an unparse function, hopefully in the future ... ! + # return ast_comments.unparse(tree) + + return ast_comments.unparse(tree) # Here we go through each respective node, slice, elt, key ... to replace outdated entries. -class NameUpdater(ast.NodeTransformer): +class NameUpdater(ast_comments.NodeTransformer): def generic_visit(self, node): # space is not yet transferred from buy/sell to entry/exit and thereby has to be skipped. - if isinstance(node, ast.keyword): + if isinstance(node, ast_comments.keyword): if node.arg == "space": return node # from here on this is the original function. - for field, old_value in ast.iter_fields(node): + for field, old_value in ast_comments.iter_fields(node): if isinstance(old_value, list): new_values = [] for value in old_value: - if isinstance(value, ast.AST): + if isinstance(value, ast_comments.AST): value = self.visit(value) if value is None: continue - elif not isinstance(value, ast.AST): + elif not isinstance(value, ast_comments.AST): new_values.extend(value) continue new_values.append(value) old_value[:] = new_values - elif isinstance(old_value, ast.AST): + elif isinstance(old_value, ast_comments.AST): new_node = self.visit(old_value) if new_node is None: delattr(node, field) @@ -163,8 +167,8 @@ class NameUpdater(ast.NodeTransformer): # node.module = "freqtrade.strategy" return node - def visit_If(self, node: ast.If): - for child in ast.iter_child_nodes(node): + def visit_If(self, node: ast_comments.If): + for child in ast_comments.iter_child_nodes(node): self.visit(child) return node @@ -175,7 +179,7 @@ class NameUpdater(ast.NodeTransformer): def visit_Attribute(self, node): if ( - isinstance(node.value, ast.Name) + isinstance(node.value, ast_comments.Name) and node.value.id == 'trades' and node.attr == 'nr_of_successful_buys' ): @@ -184,33 +188,33 @@ class NameUpdater(ast.NodeTransformer): def visit_ClassDef(self, node): # check if the class is derived from IStrategy - if any(isinstance(base, ast.Name) and + if any(isinstance(base, ast_comments.Name) and base.id == 'IStrategy' for base in node.bases): # check if the INTERFACE_VERSION variable exists has_interface_version = any( - isinstance(child, ast.Assign) and - isinstance(child.targets[0], ast.Name) and + isinstance(child, ast_comments.Assign) and + isinstance(child.targets[0], ast_comments.Name) and child.targets[0].id == 'INTERFACE_VERSION' for child in node.body ) # if the INTERFACE_VERSION variable does not exist, add it as the first child if not has_interface_version: - node.body.insert(0, ast.parse('INTERFACE_VERSION = 3').body[0]) + node.body.insert(0, ast_comments.parse('INTERFACE_VERSION = 3').body[0]) # otherwise, update its value to 3 else: for child in node.body: if ( - isinstance(child, ast.Assign) - and isinstance(child.targets[0], ast.Name) + isinstance(child, ast_comments.Assign) + and isinstance(child.targets[0], ast_comments.Name) and child.targets[0].id == 'INTERFACE_VERSION' ): - child.value = ast.parse('3').body[0].value + child.value = ast_comments.parse('3').body[0].value self.generic_visit(node) return node def visit_Subscript(self, node): - if isinstance(node.slice, ast.Constant): + if isinstance(node.slice, ast_comments.Constant): if node.slice.value in StrategyUpdater.rename_dict: # Replace the slice attributes with the values from rename_dict node.slice.value = StrategyUpdater.rename_dict[node.slice.value] @@ -232,12 +236,12 @@ class NameUpdater(ast.NodeTransformer): # sub function again needed since the structure itself is highly flexible ... def visit_elt(self, elt): - if isinstance(elt, ast.Constant) and elt.value in StrategyUpdater.rename_dict: + if isinstance(elt, ast_comments.Constant) and elt.value in StrategyUpdater.rename_dict: elt.value = StrategyUpdater.rename_dict[elt.value] if hasattr(elt, "elts"): self.visit_elts(elt.elts) if hasattr(elt, "args"): - if isinstance(elt.args, ast.arguments): + if isinstance(elt.args, ast_comments.arguments): self.visit_elts(elt.args) else: for arg in elt.args: diff --git a/tests/test_strategy_updater.py b/tests/test_strategy_updater.py index a00340427..927c5e99f 100644 --- a/tests/test_strategy_updater.py +++ b/tests/test_strategy_updater.py @@ -65,7 +65,23 @@ sell_reason == 'sell_signal' sell_reason == 'force_sell' sell_reason == 'emergency_sell' """) + modified_code9 = instance_strategy_updater.update_code(""" +# This is the 1st comment +import talib.abstract as ta +# This is the 2nd comment +import freqtrade.vendor.qtpylib.indicators as qtpylib + +class someStrategy(IStrategy): + # This is the 3rd comment + # This attribute will be overridden if the config file contains "minimal_roi" + minimal_roi = { + "0": 0.50 + } + + # This is the 4th comment + stoploss = -0.1 +""") # currently still missing: # Webhook terminology, Telegram notification settings, Strategy/Config settings @@ -108,3 +124,7 @@ sell_reason == 'emergency_sell' assert "exit_reason" in modified_code8 assert "force_exit" in modified_code8 assert "emergency_exit" in modified_code8 + + assert "This is the 1st comment" in modified_code9 + assert "This is the 2nd comment" in modified_code9 + assert "This is the 3rd comment" in modified_code9 From bcef00edeef1ea1e5611aef6d6d39eb31448195f Mon Sep 17 00:00:00 2001 From: hippocritical Date: Fri, 17 Feb 2023 21:04:26 +0100 Subject: [PATCH 016/229] changed to ast_comments, added tests for comments. --- user_data/strategies/.gitkeep | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 user_data/strategies/.gitkeep diff --git a/user_data/strategies/.gitkeep b/user_data/strategies/.gitkeep deleted file mode 100644 index e69de29bb..000000000 From fd4e27d889c4b4d192373e86b4b4a591dab8783e Mon Sep 17 00:00:00 2001 From: robcaulk Date: Tue, 21 Feb 2023 14:22:40 +0100 Subject: [PATCH 017/229] remove populate_any_indicators --- freqtrade/freqai/data_kitchen.py | 139 ++++++------------------ freqtrade/freqai/freqai_interface.py | 32 +----- freqtrade/optimize/backtesting.py | 2 +- tests/freqai/test_freqai_backtesting.py | 4 +- tests/strategy/test_interface.py | 12 -- 5 files changed, 41 insertions(+), 148 deletions(-) diff --git a/freqtrade/freqai/data_kitchen.py b/freqtrade/freqai/data_kitchen.py index 30d2509b5..ba304aca3 100644 --- a/freqtrade/freqai/data_kitchen.py +++ b/freqtrade/freqai/data_kitchen.py @@ -1315,123 +1315,54 @@ class FreqaiDataKitchen: dataframe: DataFrame = dataframe containing populated indicators """ - # this is a hack to check if the user is using the populate_any_indicators function + # check if the user is using the deprecated populate_any_indicators function new_version = inspect.getsource(strategy.populate_any_indicators) == ( inspect.getsource(IStrategy.populate_any_indicators)) - if new_version: - tfs: List[str] = self.freqai_config["feature_parameters"].get("include_timeframes") - pairs: List[str] = self.freqai_config["feature_parameters"].get( - "include_corr_pairlist", []) + if not new_version: + raise OperationalException( + "You are using the `populate_any_indicators()` function" + " which was deprecated on March 1, 2023. Please refer " + "to the strategy migration guide to use the new " + "feature_engineering_* methods: \n" + "https://www.freqtrade.io/en/stable/strategy_migration/#freqai-strategy \n" + "And the feature_engineering_* documentation: \n" + "https://www.freqtrade.io/en/latest/freqai-feature-engineering/" + ) - for tf in tfs: - if tf not in base_dataframes: - base_dataframes[tf] = pd.DataFrame() - for p in pairs: - if p not in corr_dataframes: - corr_dataframes[p] = {} - if tf not in corr_dataframes[p]: - corr_dataframes[p][tf] = pd.DataFrame() - - if not prediction_dataframe.empty: - dataframe = prediction_dataframe.copy() - else: - dataframe = base_dataframes[self.config["timeframe"]].copy() - - corr_pairs: List[str] = self.freqai_config["feature_parameters"].get( - "include_corr_pairlist", []) - dataframe = self.populate_features(dataframe.copy(), pair, strategy, - corr_dataframes, base_dataframes) - metadata = {"pair": pair} - dataframe = strategy.feature_engineering_standard(dataframe.copy(), metadata=metadata) - # ensure corr pairs are always last - for corr_pair in corr_pairs: - if pair == corr_pair: - continue # dont repeat anything from whitelist - if corr_pairs and do_corr_pairs: - dataframe = self.populate_features(dataframe.copy(), corr_pair, strategy, - corr_dataframes, base_dataframes, True) - - dataframe = strategy.set_freqai_targets(dataframe.copy(), metadata=metadata) - - self.get_unique_classes_from_labels(dataframe) - - dataframe = self.remove_special_chars_from_feature_names(dataframe) - - if self.config.get('reduce_df_footprint', False): - dataframe = reduce_dataframe_footprint(dataframe) - - return dataframe - - else: - # the user is using the populate_any_indicators functions which is deprecated - - df = self.use_strategy_to_populate_indicators_old_version( - strategy, corr_dataframes, base_dataframes, pair, - prediction_dataframe, do_corr_pairs) - return df - - def use_strategy_to_populate_indicators_old_version( - self, - strategy: IStrategy, - corr_dataframes: dict = {}, - base_dataframes: dict = {}, - pair: str = "", - prediction_dataframe: DataFrame = pd.DataFrame(), - do_corr_pairs: bool = True, - ) -> DataFrame: - """ - Use the user defined strategy for populating indicators during retrain - :param strategy: IStrategy = user defined strategy object - :param corr_dataframes: dict = dict containing the df pair dataframes - (for user defined timeframes) - :param base_dataframes: dict = dict containing the current pair dataframes - (for user defined timeframes) - :param metadata: dict = strategy furnished pair metadata - :return: - dataframe: DataFrame = dataframe containing populated indicators - """ - - # for prediction dataframe creation, we let dataprovider handle everything in the strategy - # so we create empty dictionaries, which allows us to pass None to - # `populate_any_indicators()`. Signaling we want the dp to give us the live dataframe. tfs: List[str] = self.freqai_config["feature_parameters"].get("include_timeframes") - pairs: List[str] = self.freqai_config["feature_parameters"].get("include_corr_pairlist", []) + pairs: List[str] = self.freqai_config["feature_parameters"].get( + "include_corr_pairlist", []) + + for tf in tfs: + if tf not in base_dataframes: + base_dataframes[tf] = pd.DataFrame() + for p in pairs: + if p not in corr_dataframes: + corr_dataframes[p] = {} + if tf not in corr_dataframes[p]: + corr_dataframes[p][tf] = pd.DataFrame() + if not prediction_dataframe.empty: dataframe = prediction_dataframe.copy() - for tf in tfs: - base_dataframes[tf] = None - for p in pairs: - if p not in corr_dataframes: - corr_dataframes[p] = {} - corr_dataframes[p][tf] = None else: dataframe = base_dataframes[self.config["timeframe"]].copy() - sgi = False - for tf in tfs: - if tf == tfs[-1]: - sgi = True # doing this last allows user to use all tf raw prices in labels - dataframe = strategy.populate_any_indicators( - pair, - dataframe.copy(), - tf, - informative=base_dataframes[tf], - set_generalized_indicators=sgi - ) - + corr_pairs: List[str] = self.freqai_config["feature_parameters"].get( + "include_corr_pairlist", []) + dataframe = self.populate_features(dataframe.copy(), pair, strategy, + corr_dataframes, base_dataframes) + metadata = {"pair": pair} + dataframe = strategy.feature_engineering_standard(dataframe.copy(), metadata=metadata) # ensure corr pairs are always last - for corr_pair in pairs: + for corr_pair in corr_pairs: if pair == corr_pair: continue # dont repeat anything from whitelist - for tf in tfs: - if pairs and do_corr_pairs: - dataframe = strategy.populate_any_indicators( - corr_pair, - dataframe.copy(), - tf, - informative=corr_dataframes[corr_pair][tf] - ) + if corr_pairs and do_corr_pairs: + dataframe = self.populate_features(dataframe.copy(), corr_pair, strategy, + corr_dataframes, base_dataframes, True) + + dataframe = strategy.set_freqai_targets(dataframe.copy(), metadata=metadata) self.get_unique_classes_from_labels(dataframe) diff --git a/freqtrade/freqai/freqai_interface.py b/freqtrade/freqai/freqai_interface.py index c265e42f9..c7b39b4e8 100644 --- a/freqtrade/freqai/freqai_interface.py +++ b/freqtrade/freqai/freqai_interface.py @@ -1,4 +1,3 @@ -import inspect import logging import threading import time @@ -106,8 +105,6 @@ class IFreqaiModel(ABC): self.max_system_threads = max(int(psutil.cpu_count() * 2 - 2), 1) self.can_short = True # overridden in start() with strategy.can_short - self.warned_deprecated_populate_any_indicators = False - record_params(config, self.full_path) def __getstate__(self): @@ -138,9 +135,6 @@ class IFreqaiModel(ABC): self.data_provider = strategy.dp self.can_short = strategy.can_short - # check if the strategy has deprecated populate_any_indicators function - self.check_deprecated_populate_any_indicators(strategy) - if self.live: self.inference_timer('start') self.dk = FreqaiDataKitchen(self.config, self.live, metadata["pair"]) @@ -489,7 +483,7 @@ class IFreqaiModel(ABC): "strategy is furnishing the same features as the pretrained" "model. In case of --strategy-list, please be aware that FreqAI " "requires all strategies to maintain identical " - "populate_any_indicator() functions" + "feature_engineering_* functions" ) def data_cleaning_train(self, dk: FreqaiDataKitchen) -> None: @@ -601,7 +595,7 @@ class IFreqaiModel(ABC): :param strategy: IStrategy = user defined strategy object :param dk: FreqaiDataKitchen = non-persistent data container for current coin/loop :param data_load_timerange: TimeRange = the amount of data to be loaded - for populate_any_indicators + for populating indicators (larger than new_trained_timerange so that new_trained_timerange does not contain any NaNs) """ @@ -806,7 +800,7 @@ class IFreqaiModel(ABC): logger.warning("Couldn't cache corr_pair dataframes for improved performance. " "Consider ensuring that the full coin/stake, e.g. XYZ/USD, " "is included in the column names when you are creating features " - "in `populate_any_indicators()`.") + "in `feature_engineering_*` functions.") self.get_corr_dataframes = not bool(self.corr_dataframes) elif self.corr_dataframes: dataframe = dk.attach_corr_pair_columns( @@ -933,26 +927,6 @@ class IFreqaiModel(ABC): dk.return_dataframe, saved_dataframe, how='left', left_on='date', right_on="date_pred") return dk - def check_deprecated_populate_any_indicators(self, strategy: IStrategy): - """ - Check and warn if the deprecated populate_any_indicators function is used. - :param strategy: strategy object - """ - - if not self.warned_deprecated_populate_any_indicators: - self.warned_deprecated_populate_any_indicators = True - old_version = inspect.getsource(strategy.populate_any_indicators) != ( - inspect.getsource(IStrategy.populate_any_indicators)) - - if old_version: - logger.warning("DEPRECATION WARNING: " - "You are using the deprecated populate_any_indicators function. " - "This function will raise an error on March 1 2023. " - "Please update your strategy by using " - "the new feature_engineering functions. See \n" - "https://www.freqtrade.io/en/latest/freqai-feature-engineering/" - "for details.") - # Following methods which are overridden by user made prediction models. # See freqai/prediction_models/CatboostPredictionModel.py for an example. diff --git a/freqtrade/optimize/backtesting.py b/freqtrade/optimize/backtesting.py index 065a88f40..023be9a1a 100644 --- a/freqtrade/optimize/backtesting.py +++ b/freqtrade/optimize/backtesting.py @@ -93,7 +93,7 @@ class Backtesting: if self.config.get('strategy_list'): if self.config.get('freqai', {}).get('enabled', False): logger.warning("Using --strategy-list with FreqAI REQUIRES all strategies " - "to have identical populate_any_indicators.") + "to have identical feature_engineering_* functions.") for strat in list(self.config['strategy_list']): stratconf = deepcopy(self.config) stratconf['strategy'] = strat diff --git a/tests/freqai/test_freqai_backtesting.py b/tests/freqai/test_freqai_backtesting.py index 60963e762..0a8059966 100644 --- a/tests/freqai/test_freqai_backtesting.py +++ b/tests/freqai/test_freqai_backtesting.py @@ -35,8 +35,8 @@ def test_freqai_backtest_start_backtest_list(freqai_conf, mocker, testdatadir, c args = get_args(args) bt_config = setup_optimize_configuration(args, RunMode.BACKTEST) Backtesting(bt_config) - assert log_has_re('Using --strategy-list with FreqAI REQUIRES all strategies to have identical ' - 'populate_any_indicators.', caplog) + assert log_has_re('Using --strategy-list with FreqAI REQUIRES all strategies to have identical', + caplog) Backtesting.cleanup() diff --git a/tests/strategy/test_interface.py b/tests/strategy/test_interface.py index fe562907a..87075d56d 100644 --- a/tests/strategy/test_interface.py +++ b/tests/strategy/test_interface.py @@ -291,18 +291,6 @@ def test_advise_all_indicators(default_conf, testdatadir) -> None: assert len(processed['UNITTEST/BTC']) == 103 -def test_populate_any_indicators(default_conf, testdatadir) -> None: - strategy = StrategyResolver.load_strategy(default_conf) - - timerange = TimeRange.parse_timerange('1510694220-1510700340') - data = load_data(testdatadir, '1m', ['UNITTEST/BTC'], timerange=timerange, - fill_up_missing=True) - processed = strategy.populate_any_indicators('UNITTEST/BTC', data, '5m') - assert processed == data - assert id(processed) == id(data) - assert len(processed['UNITTEST/BTC']) == 103 - - def test_freqai_not_initialized(default_conf) -> None: strategy = StrategyResolver.load_strategy(default_conf) strategy.ft_bot_start() From 7bcae7b6659ee7714eb04fbf30bb7f7d85c1356b Mon Sep 17 00:00:00 2001 From: ASU Date: Sat, 25 Feb 2023 00:26:20 +0200 Subject: [PATCH 018/229] removed redundant dependencies from environment.yml --- environment.yml | 76 ++++--------------------------------------------- 1 file changed, 6 insertions(+), 70 deletions(-) diff --git a/environment.yml b/environment.yml index 5b039e7f7..5193947cf 100644 --- a/environment.yml +++ b/environment.yml @@ -3,73 +3,9 @@ channels: - conda-forge # - defaults dependencies: -# 1/4 req main - - python>=3.8,<=3.10 - - numpy - - pandas - - pip - - - py-find-1st - - aiohttp - - SQLAlchemy - - python-telegram-bot<20.0.0 - - arrow - - cachetools - - requests - - urllib3 - - jsonschema - - TA-Lib - - tabulate - - jinja2 - - blosc - - sdnotify - - fastapi - - uvicorn - - pyjwt - - aiofiles - - psutil - - colorama - - questionary - - prompt-toolkit - - schedule - - python-dateutil - - joblib - - pyarrow - - - # ============================ - # 2/4 req dev - - - coveralls - - flake8 - - mypy - - pytest - - pytest-asyncio - - pytest-cov - - pytest-mock - - isort - - nbconvert - - # ============================ - # 3/4 req hyperopt - - - scipy - - scikit-learn - - filelock - - scikit-optimize - - progressbar2 - # ============================ - # 4/4 req plot - - - plotly - - jupyter - - - pip: - - pycoingecko - # - py_find_1st - - tables - - pytest-random-order - - ccxt - - flake8-tidy-imports - - -e . - # - python-rapidjso + - python>=3.8,<=3.10 + - pip + - libta-lib=0.4.0 # this is required for ta-lib from requirements.txt + - pip: + - -r requirements.txt + - -e . From 32ce819889c776192e12c975a4e3c507ab572843 Mon Sep 17 00:00:00 2001 From: ASU Date: Sat, 25 Feb 2023 18:23:07 +0200 Subject: [PATCH 019/229] Removed environment.yml and updated documentation --- docs/installation.md | 18 +++++++----------- environment.yml | 11 ----------- 2 files changed, 7 insertions(+), 22 deletions(-) delete mode 100644 environment.yml diff --git a/docs/installation.md b/docs/installation.md index 1c0aed7ba..6e8488b9f 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -290,10 +290,8 @@ cd freqtrade #### Freqtrade install: Conda Environment -Prepare conda-freqtrade environment, using file `environment.yml`, which exist in main freqtrade directory - ```bash -conda env create -n freqtrade-conda -f environment.yml +conda create --name freqtrade python=3.10 ``` !!! Note "Creating Conda Environment" @@ -302,12 +300,9 @@ conda env create -n freqtrade-conda -f environment.yml ```bash # choose your own packages conda env create -n [name of the environment] [python version] [packages] - - # point to file with packages - conda env create -n [name of the environment] -f [file] ``` -#### Enter/exit freqtrade-conda environment +#### Enter/exit freqtrade environment To check available environments, type @@ -319,7 +314,7 @@ Enter installed environment ```bash # enter conda environment -conda activate freqtrade-conda +conda activate freqtrade # exit conda environment - don't do it now conda deactivate @@ -329,6 +324,7 @@ Install last python dependencies with pip ```bash python3 -m pip install --upgrade pip +python3 -m pip install -r requirements.txt python3 -m pip install -e . ``` @@ -336,7 +332,7 @@ Patch conda libta-lib (Linux only) ```bash # Ensure that the environment is active! -conda activate freqtrade-conda +conda activate freqtrade cd build_helpers bash install_ta-lib.sh ${CONDA_PREFIX} nosudo @@ -355,8 +351,8 @@ conda env list # activate base environment conda activate -# activate freqtrade-conda environment -conda activate freqtrade-conda +# activate freqtrade environment +conda activate freqtrade #deactivate any conda environments conda deactivate diff --git a/environment.yml b/environment.yml deleted file mode 100644 index 5193947cf..000000000 --- a/environment.yml +++ /dev/null @@ -1,11 +0,0 @@ -name: freqtrade -channels: - - conda-forge -# - defaults -dependencies: - - python>=3.8,<=3.10 - - pip - - libta-lib=0.4.0 # this is required for ta-lib from requirements.txt - - pip: - - -r requirements.txt - - -e . From a629d455fb534510d06551be661846daf75dd117 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 13 Feb 2023 08:50:57 +0000 Subject: [PATCH 020/229] Bump sqlalchemy from 1.4.46 to 2.0.3 Bumps [sqlalchemy](https://github.com/sqlalchemy/sqlalchemy) from 1.4.46 to 2.0.3. - [Release notes](https://github.com/sqlalchemy/sqlalchemy/releases) - [Changelog](https://github.com/sqlalchemy/sqlalchemy/blob/main/CHANGES.rst) - [Commits](https://github.com/sqlalchemy/sqlalchemy/commits) --- updated-dependencies: - dependency-name: sqlalchemy dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index ea0e8ecb4..3e6c66757 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,7 +5,7 @@ pandas-ta==0.3.14b ccxt==2.8.54 cryptography==39.0.1 aiohttp==3.8.4 -SQLAlchemy==1.4.46 +SQLAlchemy==2.0.3 python-telegram-bot==13.15 arrow==1.2.3 cachetools==4.2.2 From a553a9923ad57feda53b911fac918bae1e0516ef Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 14 Feb 2023 08:51:00 +0000 Subject: [PATCH 021/229] Update types for pairlock --- freqtrade/persistence/pairlock.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/freqtrade/persistence/pairlock.py b/freqtrade/persistence/pairlock.py index 938cd14bc..b8af1421f 100644 --- a/freqtrade/persistence/pairlock.py +++ b/freqtrade/persistence/pairlock.py @@ -21,9 +21,9 @@ class PairLock(_DECL_BASE): side = Column(String(25), nullable=False, default="*") reason = Column(String(255), nullable=True) # Time the pair was locked (start time) - lock_time = Column(DateTime(), nullable=False) + lock_time: datetime = Column(DateTime(), nullable=False) # Time until the pair is locked (end time) - lock_end_time = Column(DateTime(), nullable=False, index=True) + lock_end_time: datetime = Column(DateTime(), nullable=False, index=True) active = Column(Boolean, nullable=False, default=True, index=True) From b62830031f0f70689d985d2150343fe6a6249695 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 14 Feb 2023 09:56:42 +0000 Subject: [PATCH 022/229] Dummy-type query objects --- freqtrade/persistence/pairlock.py | 2 ++ freqtrade/persistence/trade_model.py | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/freqtrade/persistence/pairlock.py b/freqtrade/persistence/pairlock.py index b8af1421f..2c4cfa3b4 100644 --- a/freqtrade/persistence/pairlock.py +++ b/freqtrade/persistence/pairlock.py @@ -13,6 +13,8 @@ class PairLock(_DECL_BASE): Pair Locks database model. """ __tablename__ = 'pairlocks' + # TODO: Properly type query. + query: Any id = Column(Integer, primary_key=True) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index c84fcec9e..e6f4f5b08 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -36,6 +36,8 @@ class Order(_DECL_BASE): Mirrors CCXT Order structure """ __tablename__ = 'orders' + # TODO: Properly type query. + query: Any # Uniqueness should be ensured over pair, order_id # its likely that order_id is unique per Pair on some exchanges. __table_args__ = (UniqueConstraint('ft_pair', 'order_id', name="_order_pair_order_id"),) @@ -1167,6 +1169,9 @@ class Trade(_DECL_BASE, LocalTrade): Note: Fields must be aligned with LocalTrade class """ __tablename__ = 'trades' + # TODO: Type query type throughout. + query: Any + _session: Any = None use_db: bool = True From 829e10ff87907bbcb0495c75e88a1e4e462a798f Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 14 Feb 2023 10:04:09 +0000 Subject: [PATCH 023/229] Improve Type for models.py --- freqtrade/persistence/models.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/freqtrade/persistence/models.py b/freqtrade/persistence/models.py index 7f851322e..38dbf212f 100644 --- a/freqtrade/persistence/models.py +++ b/freqtrade/persistence/models.py @@ -2,6 +2,7 @@ This module contains the class to persist trades into SQLite """ import logging +from typing import Any, Dict from sqlalchemy import create_engine, inspect from sqlalchemy.exc import NoSuchModuleError @@ -29,7 +30,7 @@ def init_db(db_url: str) -> None: :param db_url: Database to use :return: None """ - kwargs = {} + kwargs: Dict[str, Any] = {} if db_url == 'sqlite:///': raise OperationalException( From 9d455f58b1d643974add4b92177562a6312c77ad Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 14 Feb 2023 10:04:36 +0000 Subject: [PATCH 024/229] Improve some trade model Types --- freqtrade/persistence/trade_model.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index e6f4f5b08..c0019eaf2 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -1386,7 +1386,7 @@ class Trade(_DECL_BASE, LocalTrade): Returns List of dicts containing all Trades, including profit and trade count NOTE: Not supported in Backtesting. """ - filters = [Trade.is_open.is_(False)] + filters: List = [Trade.is_open.is_(False)] if minutes: start_date = datetime.now(timezone.utc) - timedelta(minutes=minutes) filters.append(Trade.close_date >= start_date) @@ -1419,7 +1419,7 @@ class Trade(_DECL_BASE, LocalTrade): NOTE: Not supported in Backtesting. """ - filters = [Trade.is_open.is_(False)] + filters: List = [Trade.is_open.is_(False)] if (pair is not None): filters.append(Trade.pair == pair) @@ -1452,7 +1452,7 @@ class Trade(_DECL_BASE, LocalTrade): NOTE: Not supported in Backtesting. """ - filters = [Trade.is_open.is_(False)] + filters: List = [Trade.is_open.is_(False)] if (pair is not None): filters.append(Trade.pair == pair) @@ -1485,7 +1485,7 @@ class Trade(_DECL_BASE, LocalTrade): NOTE: Not supported in Backtesting. """ - filters = [Trade.is_open.is_(False)] + filters: List = [Trade.is_open.is_(False)] if (pair is not None): filters.append(Trade.pair == pair) From 3a9d83f86c79ccdd90a2ad250dc2af47e7e9868f Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 14 Feb 2023 10:05:04 +0000 Subject: [PATCH 025/229] Mypy: define sqlalchemy plugin --- pyproject.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 6f9e5205c..71687961d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,6 +35,9 @@ warn_unused_ignores = true exclude = [ '^build_helpers\.py$' ] +plugins = [ + "sqlalchemy.ext.mypy.plugin" +] [[tool.mypy.overrides]] module = "tests.*" From 41e27ba62198c228a2e06dafeb6822381ec54030 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 14 Feb 2023 10:35:09 +0000 Subject: [PATCH 026/229] Enhance some type info --- freqtrade/freqtradebot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index 633e9dc71..ceb078669 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -633,7 +633,7 @@ class FreqtradeBot(LoggingMixin): return remaining = (trade.amount - amount) * current_exit_rate - if remaining < min_exit_stake: + if min_exit_stake and remaining < min_exit_stake: logger.info(f"Remaining amount of {remaining} would be smaller " f"than the minimum of {min_exit_stake}.") return @@ -1694,7 +1694,7 @@ class FreqtradeBot(LoggingMixin): raise DependencyException( f"Order_obj not found for {order_id}. This should not have happened.") - profit_rate = trade.close_rate if trade.close_rate else trade.close_rate_requested + profit_rate: float = trade.close_rate if trade.close_rate else trade.close_rate_requested profit_trade = trade.calc_profit(rate=profit_rate) current_rate = self.exchange.get_rate( trade.pair, side='exit', is_short=trade.is_short, refresh=False) From 3c019e0e16c64a6d488baa056f3f117c51ee3e24 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 14 Feb 2023 10:35:18 +0000 Subject: [PATCH 027/229] tentative augmented typing of Trade object --- freqtrade/freqtradebot.py | 3 +- freqtrade/persistence/trade_model.py | 72 ++++++++++++++-------------- 2 files changed, 39 insertions(+), 36 deletions(-) diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index ceb078669..adc630036 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -1737,7 +1737,8 @@ class FreqtradeBot(LoggingMixin): # def update_trade_state( - self, trade: Trade, order_id: str, action_order: Optional[Dict[str, Any]] = None, + self, trade: Trade, order_id: Optional[str], + action_order: Optional[Dict[str, Any]] = None, stoploss_order: bool = False, send_msg: bool = True) -> bool: """ Checks trades with open orders and updates the amount if necessary diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index c0019eaf2..9355d2a84 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -45,34 +45,34 @@ class Order(_DECL_BASE): id = Column(Integer, primary_key=True) ft_trade_id = Column(Integer, ForeignKey('trades.id'), index=True) - trade = relationship("Trade", back_populates="orders") + trade: List["Trade"] = relationship("Trade", back_populates="orders") # order_side can only be 'buy', 'sell' or 'stoploss' - ft_order_side = Column(String(25), nullable=False) - ft_pair = Column(String(25), nullable=False) - ft_is_open = Column(Boolean, nullable=False, default=True, index=True) - ft_amount = Column(Float(), nullable=False) - ft_price = Column(Float(), nullable=False) + ft_order_side: str = Column(String(25), nullable=False) + ft_pair: str = Column(String(25), nullable=False) + ft_is_open: bool = Column(Boolean, nullable=False, default=True, index=True) + ft_amount: float = Column(Float(), nullable=False) + ft_price: float = Column(Float(), nullable=False) order_id = Column(String(255), nullable=False, index=True) status = Column(String(255), nullable=True) symbol = Column(String(25), nullable=True) - order_type = Column(String(50), nullable=True) + # TODO: type: order_type type is Optional[str] + order_type: str = Column(String(50), nullable=True) side = Column(String(25), nullable=True) - price = Column(Float(), nullable=True) - average = Column(Float(), nullable=True) - amount = Column(Float(), nullable=True) - filled = Column(Float(), nullable=True) - remaining = Column(Float(), nullable=True) - cost = Column(Float(), nullable=True) - stop_price = Column(Float(), nullable=True) - order_date = Column(DateTime(), nullable=True, default=datetime.utcnow) + price: Optional[float] = Column(Float(), nullable=True) + average: Optional[float] = Column(Float(), nullable=True) + amount: Optional[float] = Column(Float(), nullable=True) + filled: Optional[float] = Column(Float(), nullable=True) + remaining: Optional[float] = Column(Float(), nullable=True) + cost: Optional[float] = Column(Float(), nullable=True) + stop_price: Optional[float] = Column(Float(), nullable=True) + order_date: datetime = Column(DateTime(), nullable=True, default=datetime.utcnow) order_filled_date = Column(DateTime(), nullable=True) order_update_date = Column(DateTime(), nullable=True) + funding_fee: Optional[float] = Column(Float(), nullable=True) - funding_fee = Column(Float(), nullable=True) - - ft_fee_base = Column(Float(), nullable=True) + ft_fee_base: Optional[float] = Column(Float(), nullable=True) @property def order_date_utc(self) -> datetime: @@ -1175,13 +1175,13 @@ class Trade(_DECL_BASE, LocalTrade): use_db: bool = True - id = Column(Integer, primary_key=True) + id: int = Column(Integer, primary_key=True) - orders = relationship("Order", order_by="Order.id", cascade="all, delete-orphan", - lazy="selectin", innerjoin=True) + orders: List[Order] = relationship("Order", order_by="Order.id", cascade="all, delete-orphan", + lazy="selectin", innerjoin=True) - exchange = Column(String(25), nullable=False) - pair = Column(String(25), nullable=False, index=True) + exchange: str = Column(String(25), nullable=False) + pair: str = Column(String(25), nullable=False, index=True) base_currency = Column(String(25), nullable=True) stake_currency = Column(String(25), nullable=True) is_open = Column(Boolean, nullable=False, default=True, index=True) @@ -1192,21 +1192,23 @@ class Trade(_DECL_BASE, LocalTrade): fee_close_cost = Column(Float(), nullable=True) fee_close_currency = Column(String(25), nullable=True) open_rate: float = Column(Float()) - open_rate_requested = Column(Float()) + open_rate_requested: float = Column(Float()) # open_trade_value - calculated via _calc_open_trade_value open_trade_value = Column(Float()) close_rate: Optional[float] = Column(Float()) - close_rate_requested = Column(Float()) - realized_profit = Column(Float(), default=0.0) + close_rate_requested: Optional[float] = Column(Float()) + # TODO: is the below type really correct? + realized_profit: float = Column(Float(), default=0.0) close_profit = Column(Float()) - close_profit_abs = Column(Float()) - stake_amount = Column(Float(), nullable=False) - max_stake_amount = Column(Float()) - amount = Column(Float()) - amount_requested = Column(Float()) + close_profit_abs: Optional[float] = Column(Float()) + stake_amount: float = Column(Float(), nullable=False) + max_stake_amount: Optional[float] = Column(Float()) + amount: float = Column(Float()) + amount_requested: Optional[float] = Column(Float()) open_date = Column(DateTime(), nullable=False, default=datetime.utcnow) close_date = Column(DateTime()) - open_order_id = Column(String(255)) + # TODO: open_order_id type should be Optional[str] + open_order_id: str = Column(String(255)) # absolute value of the stop loss stop_loss = Column(Float(), nullable=True, default=0.0) # percentage value of the stop loss @@ -1236,15 +1238,15 @@ class Trade(_DECL_BASE, LocalTrade): contract_size = Column(Float(), nullable=True) # Leverage trading properties - leverage = Column(Float(), nullable=True, default=1.0) - is_short = Column(Boolean, nullable=False, default=False) + leverage: float = Column(Float(), nullable=True, default=1.0) + is_short: bool = Column(Boolean, nullable=False, default=False) liquidation_price = Column(Float(), nullable=True) # Margin Trading Properties interest_rate = Column(Float(), nullable=False, default=0.0) # Futures properties - funding_fees = Column(Float(), nullable=True, default=None) + funding_fees: Optional[float] = Column(Float(), nullable=True, default=None) def __init__(self, **kwargs): super().__init__(**kwargs) From 39a658eac22a70726d4b7bfa8139ee423325731e Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 16 Feb 2023 07:04:45 +0000 Subject: [PATCH 028/229] Update DeclarativeBase --- freqtrade/persistence/base.py | 7 +++---- freqtrade/persistence/models.py | 6 +++--- freqtrade/persistence/pairlock.py | 4 ++-- freqtrade/persistence/trade_model.py | 6 +++--- 4 files changed, 11 insertions(+), 12 deletions(-) diff --git a/freqtrade/persistence/base.py b/freqtrade/persistence/base.py index fb2d561e1..2fed715d7 100644 --- a/freqtrade/persistence/base.py +++ b/freqtrade/persistence/base.py @@ -1,7 +1,6 @@ -from typing import Any - -from sqlalchemy.orm import declarative_base +from sqlalchemy.orm import DeclarativeBase -_DECL_BASE: Any = declarative_base() +class ModelBase(DeclarativeBase): + pass diff --git a/freqtrade/persistence/models.py b/freqtrade/persistence/models.py index 38dbf212f..9f90f8a74 100644 --- a/freqtrade/persistence/models.py +++ b/freqtrade/persistence/models.py @@ -10,7 +10,7 @@ from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.pool import StaticPool from freqtrade.exceptions import OperationalException -from freqtrade.persistence.base import _DECL_BASE +from freqtrade.persistence.base import ModelBase from freqtrade.persistence.migrations import check_migrate from freqtrade.persistence.pairlock import PairLock from freqtrade.persistence.trade_model import Order, Trade @@ -60,5 +60,5 @@ def init_db(db_url: str) -> None: PairLock.query = Trade._session.query_property() previous_tables = inspect(engine).get_table_names() - _DECL_BASE.metadata.create_all(engine) - check_migrate(engine, decl_base=_DECL_BASE, previous_tables=previous_tables) + ModelBase.metadata.create_all(engine) + check_migrate(engine, decl_base=ModelBase, previous_tables=previous_tables) diff --git a/freqtrade/persistence/pairlock.py b/freqtrade/persistence/pairlock.py index 2c4cfa3b4..e1f659b0a 100644 --- a/freqtrade/persistence/pairlock.py +++ b/freqtrade/persistence/pairlock.py @@ -5,10 +5,10 @@ from sqlalchemy import Boolean, Column, DateTime, Integer, String, or_ from sqlalchemy.orm import Query from freqtrade.constants import DATETIME_PRINT_FORMAT -from freqtrade.persistence.base import _DECL_BASE +from freqtrade.persistence.base import ModelBase -class PairLock(_DECL_BASE): +class PairLock(ModelBase): """ Pair Locks database model. """ diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 9355d2a84..ebec36e81 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -17,14 +17,14 @@ from freqtrade.enums import ExitType, TradingMode from freqtrade.exceptions import DependencyException, OperationalException from freqtrade.exchange import amount_to_contract_precision, price_to_precision from freqtrade.leverage import interest -from freqtrade.persistence.base import _DECL_BASE +from freqtrade.persistence.base import ModelBase from freqtrade.util import FtPrecise logger = logging.getLogger(__name__) -class Order(_DECL_BASE): +class Order(ModelBase): """ Order database model Keeps a record of all orders placed on the exchange @@ -1161,7 +1161,7 @@ class LocalTrade(): logger.info(f"New stoploss: {trade.stop_loss}.") -class Trade(_DECL_BASE, LocalTrade): +class Trade(ModelBase, LocalTrade): """ Trade database model. Also handles updating and querying trades From 0bd9b00132623db0499325545ef210ed0512e5c5 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 16 Feb 2023 07:05:57 +0000 Subject: [PATCH 029/229] Pairlock to mappedColumn --- freqtrade/persistence/pairlock.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/freqtrade/persistence/pairlock.py b/freqtrade/persistence/pairlock.py index e1f659b0a..b721cceac 100644 --- a/freqtrade/persistence/pairlock.py +++ b/freqtrade/persistence/pairlock.py @@ -1,8 +1,8 @@ from datetime import datetime, timezone from typing import Any, Dict, Optional -from sqlalchemy import Boolean, Column, DateTime, Integer, String, or_ -from sqlalchemy.orm import Query +from sqlalchemy import Boolean, DateTime, Integer, String, or_ +from sqlalchemy.orm import Query, mapped_column from freqtrade.constants import DATETIME_PRINT_FORMAT from freqtrade.persistence.base import ModelBase @@ -16,18 +16,18 @@ class PairLock(ModelBase): # TODO: Properly type query. query: Any - id = Column(Integer, primary_key=True) + id = mapped_column(Integer, primary_key=True) - pair = Column(String(25), nullable=False, index=True) + pair = mapped_column(String(25), nullable=False, index=True) # lock direction - long, short or * (for both) - side = Column(String(25), nullable=False, default="*") - reason = Column(String(255), nullable=True) + side = mapped_column(String(25), nullable=False, default="*") + reason = mapped_column(String(255), nullable=True) # Time the pair was locked (start time) - lock_time: datetime = Column(DateTime(), nullable=False) + lock_time: datetime = mapped_column(DateTime(), nullable=False) # Time until the pair is locked (end time) - lock_end_time: datetime = Column(DateTime(), nullable=False, index=True) + lock_end_time: datetime = mapped_column(DateTime(), nullable=False, index=True) - active = Column(Boolean, nullable=False, default=True, index=True) + active = mapped_column(Boolean, nullable=False, default=True, index=True) def __repr__(self): lock_time = self.lock_time.strftime(DATETIME_PRINT_FORMAT) From 98791752a9c39827385bd0c20509f560bbff88d4 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 16 Feb 2023 07:07:08 +0000 Subject: [PATCH 030/229] Update TradeModels to mapped_column --- freqtrade/persistence/trade_model.py | 152 +++++++++++++-------------- 1 file changed, 76 insertions(+), 76 deletions(-) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index ebec36e81..e8f78661e 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -7,9 +7,9 @@ from datetime import datetime, timedelta, timezone from math import isclose from typing import Any, Dict, List, Optional -from sqlalchemy import (Boolean, Column, DateTime, Enum, Float, ForeignKey, Integer, String, +from sqlalchemy import (Boolean, DateTime, Enum, Float, ForeignKey, Integer, String, UniqueConstraint, desc, func) -from sqlalchemy.orm import Query, lazyload, relationship +from sqlalchemy.orm import Query, lazyload, mapped_column, relationship from freqtrade.constants import (DATETIME_PRINT_FORMAT, MATH_CLOSE_PREC, NON_OPEN_EXCHANGE_STATES, BuySell, LongShort) @@ -42,37 +42,37 @@ class Order(ModelBase): # its likely that order_id is unique per Pair on some exchanges. __table_args__ = (UniqueConstraint('ft_pair', 'order_id', name="_order_pair_order_id"),) - id = Column(Integer, primary_key=True) - ft_trade_id = Column(Integer, ForeignKey('trades.id'), index=True) + id = mapped_column(Integer, primary_key=True) + ft_trade_id = mapped_column(Integer, ForeignKey('trades.id'), index=True) trade: List["Trade"] = relationship("Trade", back_populates="orders") # order_side can only be 'buy', 'sell' or 'stoploss' - ft_order_side: str = Column(String(25), nullable=False) - ft_pair: str = Column(String(25), nullable=False) - ft_is_open: bool = Column(Boolean, nullable=False, default=True, index=True) - ft_amount: float = Column(Float(), nullable=False) - ft_price: float = Column(Float(), nullable=False) + ft_order_side: str = mapped_column(String(25), nullable=False) + ft_pair: str = mapped_column(String(25), nullable=False) + ft_is_open: bool = mapped_column(Boolean, nullable=False, default=True, index=True) + ft_amount: float = mapped_column(Float(), nullable=False) + ft_price: float = mapped_column(Float(), nullable=False) - order_id = Column(String(255), nullable=False, index=True) - status = Column(String(255), nullable=True) - symbol = Column(String(25), nullable=True) + order_id = mapped_column(String(255), nullable=False, index=True) + status = mapped_column(String(255), nullable=True) + symbol = mapped_column(String(25), nullable=True) # TODO: type: order_type type is Optional[str] - order_type: str = Column(String(50), nullable=True) - side = Column(String(25), nullable=True) - price: Optional[float] = Column(Float(), nullable=True) - average: Optional[float] = Column(Float(), nullable=True) - amount: Optional[float] = Column(Float(), nullable=True) - filled: Optional[float] = Column(Float(), nullable=True) - remaining: Optional[float] = Column(Float(), nullable=True) - cost: Optional[float] = Column(Float(), nullable=True) - stop_price: Optional[float] = Column(Float(), nullable=True) - order_date: datetime = Column(DateTime(), nullable=True, default=datetime.utcnow) - order_filled_date = Column(DateTime(), nullable=True) - order_update_date = Column(DateTime(), nullable=True) - funding_fee: Optional[float] = Column(Float(), nullable=True) + order_type: str = mapped_column(String(50), nullable=True) + side = mapped_column(String(25), nullable=True) + price: Optional[float] = mapped_column(Float(), nullable=True) + average: Optional[float] = mapped_column(Float(), nullable=True) + amount: Optional[float] = mapped_column(Float(), nullable=True) + filled: Optional[float] = mapped_column(Float(), nullable=True) + remaining: Optional[float] = mapped_column(Float(), nullable=True) + cost: Optional[float] = mapped_column(Float(), nullable=True) + stop_price: Optional[float] = mapped_column(Float(), nullable=True) + order_date: datetime = mapped_column(DateTime(), nullable=True, default=datetime.utcnow) + order_filled_date = mapped_column(DateTime(), nullable=True) + order_update_date = mapped_column(DateTime(), nullable=True) + funding_fee: Optional[float] = mapped_column(Float(), nullable=True) - ft_fee_base: Optional[float] = Column(Float(), nullable=True) + ft_fee_base: Optional[float] = mapped_column(Float(), nullable=True) @property def order_date_utc(self) -> datetime: @@ -1175,78 +1175,78 @@ class Trade(ModelBase, LocalTrade): use_db: bool = True - id: int = Column(Integer, primary_key=True) + id: int = mapped_column(Integer, primary_key=True) orders: List[Order] = relationship("Order", order_by="Order.id", cascade="all, delete-orphan", lazy="selectin", innerjoin=True) - exchange: str = Column(String(25), nullable=False) - pair: str = Column(String(25), nullable=False, index=True) - base_currency = Column(String(25), nullable=True) - stake_currency = Column(String(25), nullable=True) - is_open = Column(Boolean, nullable=False, default=True, index=True) - fee_open = Column(Float(), nullable=False, default=0.0) - fee_open_cost = Column(Float(), nullable=True) - fee_open_currency = Column(String(25), nullable=True) - fee_close = Column(Float(), nullable=False, default=0.0) - fee_close_cost = Column(Float(), nullable=True) - fee_close_currency = Column(String(25), nullable=True) - open_rate: float = Column(Float()) - open_rate_requested: float = Column(Float()) + exchange: str = mapped_column(String(25), nullable=False) + pair: str = mapped_column(String(25), nullable=False, index=True) + base_currency = mapped_column(String(25), nullable=True) + stake_currency = mapped_column(String(25), nullable=True) + is_open = mapped_column(Boolean, nullable=False, default=True, index=True) + fee_open = mapped_column(Float(), nullable=False, default=0.0) + fee_open_cost = mapped_column(Float(), nullable=True) + fee_open_currency = mapped_column(String(25), nullable=True) + fee_close = mapped_column(Float(), nullable=False, default=0.0) + fee_close_cost = mapped_column(Float(), nullable=True) + fee_close_currency = mapped_column(String(25), nullable=True) + open_rate: float = mapped_column(Float()) + open_rate_requested: float = mapped_column(Float()) # open_trade_value - calculated via _calc_open_trade_value - open_trade_value = Column(Float()) - close_rate: Optional[float] = Column(Float()) - close_rate_requested: Optional[float] = Column(Float()) + open_trade_value = mapped_column(Float()) + close_rate: Optional[float] = mapped_column(Float()) + close_rate_requested: Optional[float] = mapped_column(Float()) # TODO: is the below type really correct? - realized_profit: float = Column(Float(), default=0.0) - close_profit = Column(Float()) - close_profit_abs: Optional[float] = Column(Float()) - stake_amount: float = Column(Float(), nullable=False) - max_stake_amount: Optional[float] = Column(Float()) - amount: float = Column(Float()) - amount_requested: Optional[float] = Column(Float()) - open_date = Column(DateTime(), nullable=False, default=datetime.utcnow) - close_date = Column(DateTime()) + realized_profit: float = mapped_column(Float(), default=0.0) + close_profit = mapped_column(Float()) + close_profit_abs: Optional[float] = mapped_column(Float()) + stake_amount: float = mapped_column(Float(), nullable=False) + max_stake_amount: Optional[float] = mapped_column(Float()) + amount: float = mapped_column(Float()) + amount_requested: Optional[float] = mapped_column(Float()) + open_date = mapped_column(DateTime(), nullable=False, default=datetime.utcnow) + close_date = mapped_column(DateTime()) # TODO: open_order_id type should be Optional[str] - open_order_id: str = Column(String(255)) + open_order_id: str = mapped_column(String(255)) # absolute value of the stop loss - stop_loss = Column(Float(), nullable=True, default=0.0) + stop_loss = mapped_column(Float(), nullable=True, default=0.0) # percentage value of the stop loss - stop_loss_pct = Column(Float(), nullable=True) + stop_loss_pct = mapped_column(Float(), nullable=True) # absolute value of the initial stop loss - initial_stop_loss = Column(Float(), nullable=True, default=0.0) + initial_stop_loss = mapped_column(Float(), nullable=True, default=0.0) # percentage value of the initial stop loss - initial_stop_loss_pct = Column(Float(), nullable=True) + initial_stop_loss_pct = mapped_column(Float(), nullable=True) # stoploss order id which is on exchange - stoploss_order_id = Column(String(255), nullable=True, index=True) + stoploss_order_id = mapped_column(String(255), nullable=True, index=True) # last update time of the stoploss order on exchange - stoploss_last_update = Column(DateTime(), nullable=True) + stoploss_last_update = mapped_column(DateTime(), nullable=True) # absolute value of the highest reached price - max_rate = Column(Float(), nullable=True, default=0.0) + max_rate = mapped_column(Float(), nullable=True, default=0.0) # Lowest price reached - min_rate = Column(Float(), nullable=True) - exit_reason = Column(String(100), nullable=True) - exit_order_status = Column(String(100), nullable=True) - strategy = Column(String(100), nullable=True) - enter_tag = Column(String(100), nullable=True) - timeframe = Column(Integer, nullable=True) + min_rate = mapped_column(Float(), nullable=True) + exit_reason = mapped_column(String(100), nullable=True) + exit_order_status = mapped_column(String(100), nullable=True) + strategy = mapped_column(String(100), nullable=True) + enter_tag = mapped_column(String(100), nullable=True) + timeframe = mapped_column(Integer, nullable=True) - trading_mode = Column(Enum(TradingMode), nullable=True) - amount_precision = Column(Float(), nullable=True) - price_precision = Column(Float(), nullable=True) - precision_mode = Column(Integer, nullable=True) - contract_size = Column(Float(), nullable=True) + trading_mode = mapped_column(Enum(TradingMode), nullable=True) + amount_precision = mapped_column(Float(), nullable=True) + price_precision = mapped_column(Float(), nullable=True) + precision_mode = mapped_column(Integer, nullable=True) + contract_size = mapped_column(Float(), nullable=True) # Leverage trading properties - leverage: float = Column(Float(), nullable=True, default=1.0) - is_short: bool = Column(Boolean, nullable=False, default=False) - liquidation_price = Column(Float(), nullable=True) + leverage: float = mapped_column(Float(), nullable=True, default=1.0) + is_short: bool = mapped_column(Boolean, nullable=False, default=False) + liquidation_price = mapped_column(Float(), nullable=True) # Margin Trading Properties - interest_rate = Column(Float(), nullable=False, default=0.0) + interest_rate = mapped_column(Float(), nullable=False, default=0.0) # Futures properties - funding_fees: Optional[float] = Column(Float(), nullable=True, default=None) + funding_fees: Optional[float] = mapped_column(Float(), nullable=True, default=None) def __init__(self, **kwargs): super().__init__(**kwargs) From 13b1a3e737689effd4dc14dcc1a60abda309375b Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 16 Feb 2023 07:14:07 +0000 Subject: [PATCH 031/229] Properly pairlock columns using mapped --- freqtrade/persistence/pairlock.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/freqtrade/persistence/pairlock.py b/freqtrade/persistence/pairlock.py index b721cceac..2c81beb85 100644 --- a/freqtrade/persistence/pairlock.py +++ b/freqtrade/persistence/pairlock.py @@ -1,8 +1,8 @@ from datetime import datetime, timezone from typing import Any, Dict, Optional -from sqlalchemy import Boolean, DateTime, Integer, String, or_ -from sqlalchemy.orm import Query, mapped_column +from sqlalchemy import String, or_ +from sqlalchemy.orm import Mapped, Query, mapped_column from freqtrade.constants import DATETIME_PRINT_FORMAT from freqtrade.persistence.base import ModelBase @@ -16,20 +16,20 @@ class PairLock(ModelBase): # TODO: Properly type query. query: Any - id = mapped_column(Integer, primary_key=True) + id: Mapped[int] = mapped_column(primary_key=True) - pair = mapped_column(String(25), nullable=False, index=True) + pair: Mapped[str] = mapped_column(String(25), nullable=False, index=True) # lock direction - long, short or * (for both) - side = mapped_column(String(25), nullable=False, default="*") - reason = mapped_column(String(255), nullable=True) + side: Mapped[str] = mapped_column(String(25), nullable=False, default="*") + reason: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) # Time the pair was locked (start time) - lock_time: datetime = mapped_column(DateTime(), nullable=False) + lock_time: Mapped[datetime] = mapped_column(nullable=False) # Time until the pair is locked (end time) - lock_end_time: datetime = mapped_column(DateTime(), nullable=False, index=True) + lock_end_time: Mapped[datetime] = mapped_column(nullable=False, index=True) - active = mapped_column(Boolean, nullable=False, default=True, index=True) + active: Mapped[bool] = mapped_column(nullable=False, default=True, index=True) - def __repr__(self): + def __repr__(self) -> str: lock_time = self.lock_time.strftime(DATETIME_PRINT_FORMAT) lock_end_time = self.lock_end_time.strftime(DATETIME_PRINT_FORMAT) return ( From bb116456a957defcb5fe422b91094cd7dd640a51 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 16 Feb 2023 07:17:56 +0000 Subject: [PATCH 032/229] Update Types for Order object --- freqtrade/persistence/trade_model.py | 52 ++++++++++++++-------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index e8f78661e..c4bfc7b1f 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -9,7 +9,7 @@ from typing import Any, Dict, List, Optional from sqlalchemy import (Boolean, DateTime, Enum, Float, ForeignKey, Integer, String, UniqueConstraint, desc, func) -from sqlalchemy.orm import Query, lazyload, mapped_column, relationship +from sqlalchemy.orm import Mapped, Query, lazyload, mapped_column, relationship from freqtrade.constants import (DATETIME_PRINT_FORMAT, MATH_CLOSE_PREC, NON_OPEN_EXCHANGE_STATES, BuySell, LongShort) @@ -42,37 +42,37 @@ class Order(ModelBase): # its likely that order_id is unique per Pair on some exchanges. __table_args__ = (UniqueConstraint('ft_pair', 'order_id', name="_order_pair_order_id"),) - id = mapped_column(Integer, primary_key=True) - ft_trade_id = mapped_column(Integer, ForeignKey('trades.id'), index=True) + id: Mapped[int] = mapped_column(Integer, primary_key=True) + ft_trade_id: Mapped[int] = mapped_column(Integer, ForeignKey('trades.id'), index=True) - trade: List["Trade"] = relationship("Trade", back_populates="orders") + trade: Mapped[List["Trade"]] = relationship("Trade", back_populates="orders") # order_side can only be 'buy', 'sell' or 'stoploss' - ft_order_side: str = mapped_column(String(25), nullable=False) - ft_pair: str = mapped_column(String(25), nullable=False) - ft_is_open: bool = mapped_column(Boolean, nullable=False, default=True, index=True) - ft_amount: float = mapped_column(Float(), nullable=False) - ft_price: float = mapped_column(Float(), nullable=False) + ft_order_side: Mapped[str] = mapped_column(String(25), nullable=False) + ft_pair: Mapped[str] = mapped_column(String(25), nullable=False) + ft_is_open: Mapped[bool] = mapped_column(nullable=False, default=True, index=True) + ft_amount: Mapped[float] = mapped_column(Float(), nullable=False) + ft_price: Mapped[float] = mapped_column(Float(), nullable=False) - order_id = mapped_column(String(255), nullable=False, index=True) - status = mapped_column(String(255), nullable=True) - symbol = mapped_column(String(25), nullable=True) + order_id: Mapped[str] = mapped_column(String(255), nullable=False, index=True) + status: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + symbol: Mapped[Optional[str]] = mapped_column(String(25), nullable=True) # TODO: type: order_type type is Optional[str] - order_type: str = mapped_column(String(50), nullable=True) - side = mapped_column(String(25), nullable=True) - price: Optional[float] = mapped_column(Float(), nullable=True) - average: Optional[float] = mapped_column(Float(), nullable=True) - amount: Optional[float] = mapped_column(Float(), nullable=True) - filled: Optional[float] = mapped_column(Float(), nullable=True) - remaining: Optional[float] = mapped_column(Float(), nullable=True) - cost: Optional[float] = mapped_column(Float(), nullable=True) - stop_price: Optional[float] = mapped_column(Float(), nullable=True) - order_date: datetime = mapped_column(DateTime(), nullable=True, default=datetime.utcnow) - order_filled_date = mapped_column(DateTime(), nullable=True) - order_update_date = mapped_column(DateTime(), nullable=True) - funding_fee: Optional[float] = mapped_column(Float(), nullable=True) + order_type: Mapped[str] = mapped_column(String(50), nullable=True) + side: Mapped[str] = mapped_column(String(25), nullable=True) + price: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) + average: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) + amount: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) + filled: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) + remaining: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) + cost: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) + stop_price: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) + order_date: Mapped[datetime] = mapped_column(nullable=True, default=datetime.utcnow) + order_filled_date: Mapped[Optional[datetime]] = mapped_column(nullable=True) + order_update_date: Mapped[Optional[datetime]] = mapped_column(nullable=True) + funding_fee: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) - ft_fee_base: Optional[float] = mapped_column(Float(), nullable=True) + ft_fee_base: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) @property def order_date_utc(self) -> datetime: From 491f49388cc1387e1aa6716f1181c150a396670b Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 16 Feb 2023 07:27:57 +0000 Subject: [PATCH 033/229] "Mapped" for trade_model --- freqtrade/persistence/trade_model.py | 95 ++++++++++++++-------------- 1 file changed, 47 insertions(+), 48 deletions(-) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index c4bfc7b1f..9db79fd8b 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -215,7 +215,7 @@ class Order(ModelBase): # Assumes backtesting will use date_last_filled_utc to calculate future funding fees. self.funding_fee = trade.funding_fees - if (self.ft_order_side == trade.entry_side): + if (self.ft_order_side == trade.entry_side and self.price): trade.open_rate = self.price trade.recalc_trade_from_orders() trade.adjust_stop_loss(trade.open_rate, trade.stop_loss_pct, refresh=True) @@ -1175,78 +1175,77 @@ class Trade(ModelBase, LocalTrade): use_db: bool = True - id: int = mapped_column(Integer, primary_key=True) + id: Mapped[int] = mapped_column(Integer, primary_key=True) - orders: List[Order] = relationship("Order", order_by="Order.id", cascade="all, delete-orphan", - lazy="selectin", innerjoin=True) + orders: Mapped[List[Order]] = relationship( + "Order", order_by="Order.id", cascade="all, delete-orphan", lazy="selectin", + innerjoin=True) - exchange: str = mapped_column(String(25), nullable=False) - pair: str = mapped_column(String(25), nullable=False, index=True) + exchange: Mapped[str] = mapped_column(String(25), nullable=False) + pair: Mapped[str] = mapped_column(String(25), nullable=False, index=True) base_currency = mapped_column(String(25), nullable=True) stake_currency = mapped_column(String(25), nullable=True) - is_open = mapped_column(Boolean, nullable=False, default=True, index=True) - fee_open = mapped_column(Float(), nullable=False, default=0.0) - fee_open_cost = mapped_column(Float(), nullable=True) - fee_open_currency = mapped_column(String(25), nullable=True) - fee_close = mapped_column(Float(), nullable=False, default=0.0) - fee_close_cost = mapped_column(Float(), nullable=True) - fee_close_currency = mapped_column(String(25), nullable=True) - open_rate: float = mapped_column(Float()) + is_open: Mapped[bool] = mapped_column(nullable=False, default=True, index=True) + fee_open: Mapped[float] = mapped_column(Float(), nullable=False, default=0.0) + fee_open_cost: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) + fee_open_currency: Mapped[Optional[str]] = mapped_column(String(25), nullable=True) + fee_close: Mapped[Optional[float]] = mapped_column(Float(), nullable=False, default=0.0) + fee_close_cost: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) + fee_close_currency: Mapped[Optional[str]] = mapped_column(String(25), nullable=True) + open_rate: Mapped[float] = mapped_column(Float()) open_rate_requested: float = mapped_column(Float()) # open_trade_value - calculated via _calc_open_trade_value open_trade_value = mapped_column(Float()) close_rate: Optional[float] = mapped_column(Float()) close_rate_requested: Optional[float] = mapped_column(Float()) - # TODO: is the below type really correct? - realized_profit: float = mapped_column(Float(), default=0.0) - close_profit = mapped_column(Float()) - close_profit_abs: Optional[float] = mapped_column(Float()) - stake_amount: float = mapped_column(Float(), nullable=False) - max_stake_amount: Optional[float] = mapped_column(Float()) - amount: float = mapped_column(Float()) - amount_requested: Optional[float] = mapped_column(Float()) - open_date = mapped_column(DateTime(), nullable=False, default=datetime.utcnow) - close_date = mapped_column(DateTime()) - # TODO: open_order_id type should be Optional[str] - open_order_id: str = mapped_column(String(255)) + realized_profit: Mapped[float] = mapped_column(Float(), default=0.0) + close_profit: Mapped[Optional[float]] = mapped_column(Float()) + close_profit_abs: Mapped[Optional[float]] = mapped_column(Float()) + stake_amount: Mapped[float] = mapped_column(Float(), nullable=False) + max_stake_amount: Mapped[Optional[float]] = mapped_column(Float()) + amount: Mapped[float] = mapped_column(Float()) + amount_requested: Mapped[Optional[float]] = mapped_column(Float()) + open_date: Mapped[datetime] = mapped_column(nullable=False, default=datetime.utcnow) + close_date: Mapped[Optional[datetime]] = mapped_column() + open_order_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) # absolute value of the stop loss - stop_loss = mapped_column(Float(), nullable=True, default=0.0) + stop_loss: Mapped[Optional[float]] = mapped_column(Float(), nullable=True, default=0.0) # percentage value of the stop loss - stop_loss_pct = mapped_column(Float(), nullable=True) + stop_loss_pct: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) # absolute value of the initial stop loss - initial_stop_loss = mapped_column(Float(), nullable=True, default=0.0) + initial_stop_loss: Mapped[Optional[float]] = mapped_column(Float(), nullable=True, default=0.0) # percentage value of the initial stop loss - initial_stop_loss_pct = mapped_column(Float(), nullable=True) + initial_stop_loss_pct: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) # stoploss order id which is on exchange - stoploss_order_id = mapped_column(String(255), nullable=True, index=True) + stoploss_order_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True, index=True) # last update time of the stoploss order on exchange - stoploss_last_update = mapped_column(DateTime(), nullable=True) + stoploss_last_update: Mapped[Optional[datetime]] = mapped_column(nullable=True) # absolute value of the highest reached price - max_rate = mapped_column(Float(), nullable=True, default=0.0) + max_rate: Mapped[Optional[float]] = mapped_column(Float(), nullable=True, default=0.0) # Lowest price reached - min_rate = mapped_column(Float(), nullable=True) - exit_reason = mapped_column(String(100), nullable=True) - exit_order_status = mapped_column(String(100), nullable=True) - strategy = mapped_column(String(100), nullable=True) - enter_tag = mapped_column(String(100), nullable=True) - timeframe = mapped_column(Integer, nullable=True) + min_rate: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) + exit_reason: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) + exit_order_status: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) + strategy: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) + enter_tag: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) + timeframe: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) trading_mode = mapped_column(Enum(TradingMode), nullable=True) - amount_precision = mapped_column(Float(), nullable=True) - price_precision = mapped_column(Float(), nullable=True) - precision_mode = mapped_column(Integer, nullable=True) - contract_size = mapped_column(Float(), nullable=True) + amount_precision: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) + price_precision: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) + precision_mode: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + contract_size: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) # Leverage trading properties - leverage: float = mapped_column(Float(), nullable=True, default=1.0) - is_short: bool = mapped_column(Boolean, nullable=False, default=False) - liquidation_price = mapped_column(Float(), nullable=True) + leverage: Mapped[Optional[float]] = mapped_column(Float(), nullable=True, default=1.0) + is_short: Mapped[bool] = mapped_column(nullable=False, default=False) + liquidation_price: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) # Margin Trading Properties - interest_rate = mapped_column(Float(), nullable=False, default=0.0) + interest_rate: Mapped[Optional[float]] = mapped_column(Float(), nullable=False, default=0.0) # Futures properties - funding_fees: Optional[float] = mapped_column(Float(), nullable=True, default=None) + funding_fees: Mapped[Optional[float]] = mapped_column(Float(), nullable=True, default=None) def __init__(self, **kwargs): super().__init__(**kwargs) From 47b66f322076ac22b986bac0930016adcf3d66bf Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 16 Feb 2023 08:40:34 +0000 Subject: [PATCH 034/229] More fun with types --- freqtrade/persistence/trade_model.py | 10 +++++----- freqtrade/rpc/rpc.py | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 9db79fd8b..be296c52c 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -1183,8 +1183,8 @@ class Trade(ModelBase, LocalTrade): exchange: Mapped[str] = mapped_column(String(25), nullable=False) pair: Mapped[str] = mapped_column(String(25), nullable=False, index=True) - base_currency = mapped_column(String(25), nullable=True) - stake_currency = mapped_column(String(25), nullable=True) + base_currency: Mapped[Optional[str]] = mapped_column(String(25), nullable=True) + stake_currency: Mapped[Optional[str]] = mapped_column(String(25), nullable=True) is_open: Mapped[bool] = mapped_column(nullable=False, default=True, index=True) fee_open: Mapped[float] = mapped_column(Float(), nullable=False, default=0.0) fee_open_cost: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) @@ -1209,7 +1209,7 @@ class Trade(ModelBase, LocalTrade): close_date: Mapped[Optional[datetime]] = mapped_column() open_order_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) # absolute value of the stop loss - stop_loss: Mapped[Optional[float]] = mapped_column(Float(), nullable=True, default=0.0) + stop_loss: Mapped[float] = mapped_column(Float(), nullable=True, default=0.0) # percentage value of the stop loss stop_loss_pct: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) # absolute value of the initial stop loss @@ -1230,14 +1230,14 @@ class Trade(ModelBase, LocalTrade): enter_tag: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) timeframe: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) - trading_mode = mapped_column(Enum(TradingMode), nullable=True) + trading_mode: Mapped[TradingMode] = mapped_column(Enum(TradingMode), nullable=True) amount_precision: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) price_precision: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) precision_mode: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) contract_size: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) # Leverage trading properties - leverage: Mapped[Optional[float]] = mapped_column(Float(), nullable=True, default=1.0) + leverage: Mapped[float] = mapped_column(Float(), nullable=True, default=1.0) is_short: Mapped[bool] = mapped_column(nullable=False, default=False) liquidation_price: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 82f892101..0c1a8fbbd 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -506,7 +506,7 @@ class RPC: trades_df = DataFrame([{'close_date': trade.close_date.strftime(DATETIME_PRINT_FORMAT), 'profit_abs': trade.close_profit_abs} - for trade in trades if not trade.is_open]) + for trade in trades if not trade.is_open and trade.close_date]) max_drawdown_abs = 0.0 max_drawdown = 0.0 if len(trades_df) > 0: From e59eaf33e09f2b613c44f3ac67a326140c8b6176 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 16 Feb 2023 08:51:32 +0000 Subject: [PATCH 035/229] Update _session to session --- freqtrade/commands/db_commands.py | 2 +- freqtrade/persistence/models.py | 10 ++++++---- tests/persistence/test_migrations.py | 4 ++-- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/freqtrade/commands/db_commands.py b/freqtrade/commands/db_commands.py index c424016b1..b4997582d 100644 --- a/freqtrade/commands/db_commands.py +++ b/freqtrade/commands/db_commands.py @@ -20,7 +20,7 @@ def start_convert_db(args: Dict[str, Any]) -> None: config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE) init_db(config['db_url']) - session_target = Trade._session + session_target = Trade.session init_db(config['db_url_from']) logger.info("Starting db migration.") diff --git a/freqtrade/persistence/models.py b/freqtrade/persistence/models.py index 9f90f8a74..f4058b4eb 100644 --- a/freqtrade/persistence/models.py +++ b/freqtrade/persistence/models.py @@ -54,10 +54,12 @@ def init_db(db_url: str) -> None: # https://docs.sqlalchemy.org/en/13/orm/contextual.html#thread-local-scope # Scoped sessions proxy requests to the appropriate thread-local session. # We should use the scoped_session object - not a seperately initialized version - Trade._session = scoped_session(sessionmaker(bind=engine, autoflush=False)) - Trade.query = Trade._session.query_property() - Order.query = Trade._session.query_property() - PairLock.query = Trade._session.query_property() + Trade.session = scoped_session(sessionmaker(bind=engine, autoflush=False)) + Order.session = Trade.session + PairLock.session = Trade.session + Trade.query = Trade.session.query_property() + Order.query = Trade.session.query_property() + PairLock.query = Trade.session.query_property() previous_tables = inspect(engine).get_table_names() ModelBase.metadata.create_all(engine) diff --git a/tests/persistence/test_migrations.py b/tests/persistence/test_migrations.py index 2a6959d58..d49b7d207 100644 --- a/tests/persistence/test_migrations.py +++ b/tests/persistence/test_migrations.py @@ -22,7 +22,7 @@ def test_init_create_session(default_conf): # Check if init create a session init_db(default_conf['db_url']) assert hasattr(Trade, '_session') - assert 'scoped_session' in type(Trade._session).__name__ + assert 'scoped_session' in type(Trade.session).__name__ def test_init_custom_db_url(default_conf, tmpdir): @@ -34,7 +34,7 @@ def test_init_custom_db_url(default_conf, tmpdir): init_db(default_conf['db_url']) assert Path(filename).is_file() - r = Trade._session.execute(text("PRAGMA journal_mode")) + r = Trade.session.execute(text("PRAGMA journal_mode")) assert r.first() == ('wal',) From 608a7c2d384e588233d92e37c795e24c7689c0f8 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 16 Feb 2023 09:02:57 +0000 Subject: [PATCH 036/229] Add safe_close_rate --- freqtrade/freqtradebot.py | 4 ++-- freqtrade/persistence/trade_model.py | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index adc630036..0bed27cb9 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -1639,7 +1639,7 @@ class FreqtradeBot(LoggingMixin): profit = trade.calc_profit(rate=order_rate, amount=amount, open_rate=trade.open_rate) profit_ratio = trade.calc_profit_ratio(order_rate, amount, trade.open_rate) else: - order_rate = trade.close_rate if trade.close_rate else trade.close_rate_requested + order_rate = trade.safe_close_rate profit = trade.calc_profit(rate=order_rate) + (0.0 if fill else trade.realized_profit) profit_ratio = trade.calc_profit_ratio(order_rate) amount = trade.amount @@ -1694,7 +1694,7 @@ class FreqtradeBot(LoggingMixin): raise DependencyException( f"Order_obj not found for {order_id}. This should not have happened.") - profit_rate: float = trade.close_rate if trade.close_rate else trade.close_rate_requested + profit_rate: float = trade.safe_close_rate profit_trade = trade.calc_profit(rate=profit_rate) current_rate = self.exchange.get_rate( trade.pair, side='exit', is_short=trade.is_short, refresh=False) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index be296c52c..091152196 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -1065,6 +1065,10 @@ class LocalTrade(): """ DEPRECATED! Please use exit_reason instead.""" return self.exit_reason + @property + def safe_close_rate(self) -> float: + return self.close_rate or self.close_rate_requested or 0.0 + @staticmethod def get_trades_proxy(*, pair: Optional[str] = None, is_open: Optional[bool] = None, open_date: Optional[datetime] = None, From 65a5cf64df91f51e5c82bf0fecc8821fa59cd717 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 16 Feb 2023 09:03:32 +0000 Subject: [PATCH 037/229] Re-type session --- freqtrade/persistence/trade_model.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 091152196..b3ccf7949 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -1175,7 +1175,7 @@ class Trade(ModelBase, LocalTrade): __tablename__ = 'trades' # TODO: Type query type throughout. query: Any - _session: Any = None + session: Any = None use_db: bool = True From 101d9ab87f6208375fc1e990dff38ed275e4cbce Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 19 Feb 2023 19:51:25 +0100 Subject: [PATCH 038/229] Improvements - tests runnable again --- freqtrade/persistence/pairlock.py | 4 ++-- freqtrade/persistence/trade_model.py | 17 ++++++++--------- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/freqtrade/persistence/pairlock.py b/freqtrade/persistence/pairlock.py index 2c81beb85..f8c0586a4 100644 --- a/freqtrade/persistence/pairlock.py +++ b/freqtrade/persistence/pairlock.py @@ -1,5 +1,5 @@ from datetime import datetime, timezone -from typing import Any, Dict, Optional +from typing import Any, ClassVar, Dict, Optional from sqlalchemy import String, or_ from sqlalchemy.orm import Mapped, Query, mapped_column @@ -14,7 +14,7 @@ class PairLock(ModelBase): """ __tablename__ = 'pairlocks' # TODO: Properly type query. - query: Any + query: ClassVar[Any] id: Mapped[int] = mapped_column(primary_key=True) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index b3ccf7949..4b7a09cbe 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -5,10 +5,9 @@ import logging from collections import defaultdict from datetime import datetime, timedelta, timezone from math import isclose -from typing import Any, Dict, List, Optional +from typing import Any, ClassVar, Dict, List, Optional -from sqlalchemy import (Boolean, DateTime, Enum, Float, ForeignKey, Integer, String, - UniqueConstraint, desc, func) +from sqlalchemy import Enum, Float, ForeignKey, Integer, String, UniqueConstraint, desc, func from sqlalchemy.orm import Mapped, Query, lazyload, mapped_column, relationship from freqtrade.constants import (DATETIME_PRINT_FORMAT, MATH_CLOSE_PREC, NON_OPEN_EXCHANGE_STATES, @@ -37,7 +36,7 @@ class Order(ModelBase): """ __tablename__ = 'orders' # TODO: Properly type query. - query: Any + query: ClassVar[Any] # Uniqueness should be ensured over pair, order_id # its likely that order_id is unique per Pair on some exchanges. __table_args__ = (UniqueConstraint('ft_pair', 'order_id', name="_order_pair_order_id"),) @@ -1174,8 +1173,8 @@ class Trade(ModelBase, LocalTrade): """ __tablename__ = 'trades' # TODO: Type query type throughout. - query: Any - session: Any = None + query: ClassVar[Any] + session: ClassVar[Any] = None use_db: bool = True @@ -1197,11 +1196,11 @@ class Trade(ModelBase, LocalTrade): fee_close_cost: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) fee_close_currency: Mapped[Optional[str]] = mapped_column(String(25), nullable=True) open_rate: Mapped[float] = mapped_column(Float()) - open_rate_requested: float = mapped_column(Float()) + open_rate_requested: Mapped[float] = mapped_column(Float()) # open_trade_value - calculated via _calc_open_trade_value open_trade_value = mapped_column(Float()) - close_rate: Optional[float] = mapped_column(Float()) - close_rate_requested: Optional[float] = mapped_column(Float()) + close_rate: Mapped[Optional[float]] = mapped_column(Float()) + close_rate_requested: Mapped[Optional[float]] = mapped_column(Float()) realized_profit: Mapped[float] = mapped_column(Float(), default=0.0) close_profit: Mapped[Optional[float]] = mapped_column(Float()) close_profit_abs: Mapped[Optional[float]] = mapped_column(Float()) From 0691bbaad9aeda6fdcc1ec9a9c75edf358974931 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 19 Feb 2023 20:18:46 +0100 Subject: [PATCH 039/229] Update some db types --- freqtrade/persistence/trade_model.py | 2 +- tests/persistence/test_migrations.py | 2 +- tests/persistence/test_persistence.py | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 4b7a09cbe..abb989940 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -1196,7 +1196,7 @@ class Trade(ModelBase, LocalTrade): fee_close_cost: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) fee_close_currency: Mapped[Optional[str]] = mapped_column(String(25), nullable=True) open_rate: Mapped[float] = mapped_column(Float()) - open_rate_requested: Mapped[float] = mapped_column(Float()) + open_rate_requested: Mapped[float] = mapped_column(Float(), nullable=True) # open_trade_value - calculated via _calc_open_trade_value open_trade_value = mapped_column(Float()) close_rate: Mapped[Optional[float]] = mapped_column(Float()) diff --git a/tests/persistence/test_migrations.py b/tests/persistence/test_migrations.py index d49b7d207..5254164c1 100644 --- a/tests/persistence/test_migrations.py +++ b/tests/persistence/test_migrations.py @@ -21,7 +21,7 @@ spot, margin, futures = TradingMode.SPOT, TradingMode.MARGIN, TradingMode.FUTURE def test_init_create_session(default_conf): # Check if init create a session init_db(default_conf['db_url']) - assert hasattr(Trade, '_session') + assert hasattr(Trade, 'session') assert 'scoped_session' in type(Trade.session).__name__ diff --git a/tests/persistence/test_persistence.py b/tests/persistence/test_persistence.py index d06f05179..6d907ccf0 100644 --- a/tests/persistence/test_persistence.py +++ b/tests/persistence/test_persistence.py @@ -2440,6 +2440,7 @@ def test_select_filled_orders(fee): def test_order_to_ccxt(limit_buy_order_open): order = Order.parse_from_ccxt_object(limit_buy_order_open, 'mocked', 'buy') + order.ft_trade_id = 1 order.query.session.add(order) Order.query.session.commit() From f6b3998bbda8c8ac22e7c13f40b2dfe40217212e Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 19 Feb 2023 20:23:04 +0100 Subject: [PATCH 040/229] Fix backtesting type incompatibilities --- freqtrade/freqtradebot.py | 3 ++- freqtrade/optimize/backtesting.py | 21 ++++++++++++--------- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index 0bed27cb9..ad0628c59 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -1330,7 +1330,8 @@ class FreqtradeBot(LoggingMixin): # place new order only if new price is supplied self.execute_entry( pair=trade.pair, - stake_amount=(order_obj.remaining * order_obj.price / trade.leverage), + stake_amount=( + order_obj.safe_remaining * order_obj.safe_price / trade.leverage), price=adjusted_entry_price, trade=trade, is_short=trade.is_short, diff --git a/freqtrade/optimize/backtesting.py b/freqtrade/optimize/backtesting.py index 065a88f40..7f3036037 100644 --- a/freqtrade/optimize/backtesting.py +++ b/freqtrade/optimize/backtesting.py @@ -563,7 +563,7 @@ class Backtesting: pos_trade = self._get_exit_for_signal(trade, row, exit_, amount) if pos_trade is not None: order = pos_trade.orders[-1] - if self._get_order_filled(order.price, row): + if self._get_order_filled(order.ft_price, row): order.close_bt_order(current_date, trade) trade.recalc_trade_from_orders() self.wallets.update() @@ -664,6 +664,7 @@ class Backtesting: side=trade.exit_side, order_type=order_type, status="open", + ft_price=close_rate, price=close_rate, average=close_rate, amount=amount, @@ -887,6 +888,7 @@ class Backtesting: order_date=current_time, order_filled_date=current_time, order_update_date=current_time, + ft_price=propose_rate, price=propose_rate, average=propose_rate, amount=amount, @@ -895,7 +897,7 @@ class Backtesting: cost=stake_amount + trade.fee_open, ) trade.orders.append(order) - if pos_adjust and self._get_order_filled(order.price, row): + if pos_adjust and self._get_order_filled(order.ft_price, row): order.close_bt_order(current_time, trade) else: trade.open_order_id = str(self.order_id_counter) @@ -1008,15 +1010,15 @@ class Backtesting: # only check on new candles for open entry orders if order.side == trade.entry_side and current_time > order.order_date_utc: requested_rate = strategy_safe_wrapper(self.strategy.adjust_entry_price, - default_retval=order.price)( + default_retval=order.ft_price)( trade=trade, # type: ignore[arg-type] order=order, pair=trade.pair, current_time=current_time, - proposed_rate=row[OPEN_IDX], current_order_rate=order.price, + proposed_rate=row[OPEN_IDX], current_order_rate=order.ft_price, entry_tag=trade.enter_tag, side=trade.trade_direction ) # default value is current order price # cancel existing order whenever a new rate is requested (or None) - if requested_rate == order.price: + if requested_rate == order.ft_price: # assumption: there can't be multiple open entry orders at any given time return False else: @@ -1028,7 +1030,8 @@ class Backtesting: if requested_rate: self._enter_trade(pair=trade.pair, row=row, trade=trade, requested_rate=requested_rate, - requested_stake=(order.remaining * order.price / trade.leverage), + requested_stake=( + order.safe_remaining * order.ft_price / trade.leverage), direction='short' if trade.is_short else 'long') self.replaced_entry_orders += 1 else: @@ -1095,7 +1098,7 @@ class Backtesting: for trade in list(LocalTrade.bt_trades_open_pp[pair]): # 3. Process entry orders. order = trade.select_order(trade.entry_side, is_open=True) - if order and self._get_order_filled(order.price, row): + if order and self._get_order_filled(order.ft_price, row): order.close_bt_order(current_time, trade) trade.open_order_id = None self.wallets.update() @@ -1106,7 +1109,7 @@ class Backtesting: # 5. Process exit orders. order = trade.select_order(trade.exit_side, is_open=True) - if order and self._get_order_filled(order.price, row): + if order and self._get_order_filled(order.ft_price, row): order.close_bt_order(current_time, trade) trade.open_order_id = None sub_trade = order.safe_amount_after_fee != trade.amount @@ -1115,7 +1118,7 @@ class Backtesting: trade.recalc_trade_from_orders() else: trade.close_date = current_time - trade.close(order.price, show_msg=False) + trade.close(order.ft_price, show_msg=False) # logger.debug(f"{pair} - Backtesting exit {trade}") LocalTrade.close_bt_trade(trade) From 8765e3a4d63a30e1711d6701553966d74d867694 Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 20 Feb 2023 07:12:09 +0100 Subject: [PATCH 041/229] Fix some Type issues --- freqtrade/rpc/rpc.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 0c1a8fbbd..f8537b0f8 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -189,8 +189,8 @@ class RPC: else: # Closed trade ... current_rate = trade.close_rate - current_profit = trade.close_profit - current_profit_abs = trade.close_profit_abs + current_profit = trade.close_profit or 0.0 + current_profit_abs = trade.close_profit_abs or 0.0 total_profit_abs = trade.realized_profit + current_profit_abs # Calculate fiat profit @@ -449,11 +449,11 @@ class RPC: durations.append((trade.close_date - trade.open_date).total_seconds()) if not trade.is_open: - profit_ratio = trade.close_profit - profit_abs = trade.close_profit_abs + profit_ratio = trade.close_profit or 0.0 + profit_abs = trade.close_profit_abs or 0.0 profit_closed_coin.append(profit_abs) profit_closed_ratio.append(profit_ratio) - if trade.close_profit >= 0: + if profit_ratio >= 0: winning_trades += 1 winning_profit += profit_abs else: From c2c039151cbcdc176ecc506bf6ee6b8fc2d311f4 Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 20 Feb 2023 18:26:32 +0100 Subject: [PATCH 042/229] Improve typesafety around trade object --- freqtrade/freqtradebot.py | 9 +++++++-- freqtrade/rpc/rpc.py | 2 +- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index ad0628c59..cec7176f6 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -1314,7 +1314,7 @@ class FreqtradeBot(LoggingMixin): default_retval=order_obj.price)( trade=trade, order=order_obj, pair=trade.pair, current_time=datetime.now(timezone.utc), proposed_rate=proposed_rate, - current_order_rate=order_obj.price, entry_tag=trade.enter_tag, + current_order_rate=order_obj.safe_price, entry_tag=trade.enter_tag, side=trade.entry_side) replacing = True @@ -1345,6 +1345,8 @@ class FreqtradeBot(LoggingMixin): """ for trade in Trade.get_open_order_trades(): + if not trade.open_order_id: + continue try: order = self.exchange.fetch_order(trade.open_order_id, trade.pair) except (ExchangeError): @@ -1369,6 +1371,9 @@ class FreqtradeBot(LoggingMixin): """ was_trade_fully_canceled = False side = trade.entry_side.capitalize() + if not trade.open_order_id: + logger.warning(f"No open order for {trade}.") + return False # Cancelled orders may have the status of 'canceled' or 'closed' if order['status'] not in constants.NON_OPEN_EXCHANGE_STATES: @@ -1455,7 +1460,7 @@ class FreqtradeBot(LoggingMixin): return False try: - co = self.exchange.cancel_order_with_result(trade.open_order_id, trade.pair, + co = self.exchange.cancel_order_with_result(order['id'], trade.pair, trade.amount) except InvalidOrderException: logger.exception( diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index f8537b0f8..38f478f4c 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -410,7 +410,7 @@ class RPC: exit_reasons[trade.exit_reason][trade_win_loss(trade)] += 1 # Duration - dur: Dict[str, List[int]] = {'wins': [], 'draws': [], 'losses': []} + dur: Dict[str, List[float]] = {'wins': [], 'draws': [], 'losses': []} for trade in trades: if trade.close_date is not None and trade.open_date is not None: trade_dur = (trade.close_date - trade.open_date).total_seconds() From db4f4498dc6583e6a1eb9e3183f6b11c6232de96 Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 20 Feb 2023 20:00:01 +0100 Subject: [PATCH 043/229] Experimentally type query property ... --- freqtrade/persistence/models.py | 3 ++- freqtrade/persistence/pairlock.py | 6 ++++-- freqtrade/persistence/trade_model.py | 12 +++++++----- 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/freqtrade/persistence/models.py b/freqtrade/persistence/models.py index f4058b4eb..b94be950a 100644 --- a/freqtrade/persistence/models.py +++ b/freqtrade/persistence/models.py @@ -6,7 +6,7 @@ from typing import Any, Dict from sqlalchemy import create_engine, inspect from sqlalchemy.exc import NoSuchModuleError -from sqlalchemy.orm import scoped_session, sessionmaker +from sqlalchemy.orm import Session, scoped_session, sessionmaker from sqlalchemy.pool import StaticPool from freqtrade.exceptions import OperationalException @@ -20,6 +20,7 @@ logger = logging.getLogger(__name__) _SQL_DOCS_URL = 'http://docs.sqlalchemy.org/en/latest/core/engines.html#database-urls' +SessionType = scoped_session[Session] def init_db(db_url: str) -> None: diff --git a/freqtrade/persistence/pairlock.py b/freqtrade/persistence/pairlock.py index f8c0586a4..b10d74693 100644 --- a/freqtrade/persistence/pairlock.py +++ b/freqtrade/persistence/pairlock.py @@ -3,9 +3,11 @@ from typing import Any, ClassVar, Dict, Optional from sqlalchemy import String, or_ from sqlalchemy.orm import Mapped, Query, mapped_column +from sqlalchemy.orm.scoping import _QueryDescriptorType from freqtrade.constants import DATETIME_PRINT_FORMAT from freqtrade.persistence.base import ModelBase +from freqtrade.persistence.models import SessionType class PairLock(ModelBase): @@ -13,8 +15,8 @@ class PairLock(ModelBase): Pair Locks database model. """ __tablename__ = 'pairlocks' - # TODO: Properly type query. - query: ClassVar[Any] + query: ClassVar[_QueryDescriptorType] + session: ClassVar[SessionType] id: Mapped[int] = mapped_column(primary_key=True) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index abb989940..10643db17 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -9,6 +9,7 @@ from typing import Any, ClassVar, Dict, List, Optional from sqlalchemy import Enum, Float, ForeignKey, Integer, String, UniqueConstraint, desc, func from sqlalchemy.orm import Mapped, Query, lazyload, mapped_column, relationship +from sqlalchemy.orm.scoping import _QueryDescriptorType from freqtrade.constants import (DATETIME_PRINT_FORMAT, MATH_CLOSE_PREC, NON_OPEN_EXCHANGE_STATES, BuySell, LongShort) @@ -17,6 +18,7 @@ from freqtrade.exceptions import DependencyException, OperationalException from freqtrade.exchange import amount_to_contract_precision, price_to_precision from freqtrade.leverage import interest from freqtrade.persistence.base import ModelBase +from freqtrade.persistence.models import SessionType from freqtrade.util import FtPrecise @@ -35,8 +37,9 @@ class Order(ModelBase): Mirrors CCXT Order structure """ __tablename__ = 'orders' - # TODO: Properly type query. - query: ClassVar[Any] + query: ClassVar[_QueryDescriptorType] + session: ClassVar[SessionType] + # Uniqueness should be ensured over pair, order_id # its likely that order_id is unique per Pair on some exchanges. __table_args__ = (UniqueConstraint('ft_pair', 'order_id', name="_order_pair_order_id"),) @@ -1172,9 +1175,8 @@ class Trade(ModelBase, LocalTrade): Note: Fields must be aligned with LocalTrade class """ __tablename__ = 'trades' - # TODO: Type query type throughout. - query: ClassVar[Any] - session: ClassVar[Any] = None + query: ClassVar[_QueryDescriptorType] + session: ClassVar[SessionType] = None use_db: bool = True From b65cff0adcd6498a0dfe288a97c93488c3bb7fab Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 20 Feb 2023 20:22:41 +0100 Subject: [PATCH 044/229] Update "Query" type --- freqtrade/persistence/trade_model.py | 2 +- freqtrade/rpc/rpc.py | 9 +++++---- freqtrade/rpc/telegram.py | 10 +++++++--- 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 10643db17..0f85528e0 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -1305,7 +1305,7 @@ class Trade(ModelBase, LocalTrade): ) @staticmethod - def get_trades(trade_filter=None, include_orders: bool = True) -> Query: + def get_trades(trade_filter=None, include_orders: bool = True) -> Query['Trade']: """ Helper function to query Trades using filters. NOTE: Not supported in Backtesting. diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 38f478f4c..8692c477f 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -373,13 +373,13 @@ class RPC: def _rpc_trade_history(self, limit: int, offset: int = 0, order_by_id: bool = False) -> Dict: """ Returns the X last trades """ - order_by = Trade.id if order_by_id else Trade.close_date.desc() + order_by: Any = Trade.id if order_by_id else Trade.close_date.desc() if limit: trades = Trade.get_trades([Trade.is_open.is_(False)]).order_by( order_by).limit(limit).offset(offset) else: trades = Trade.get_trades([Trade.is_open.is_(False)]).order_by( - Trade.close_date.desc()).all() + Trade.close_date.desc()) output = [trade.to_json() for trade in trades] @@ -401,7 +401,7 @@ class RPC: return 'losses' else: return 'draws' - trades: List[Trade] = Trade.get_trades([Trade.is_open.is_(False)], include_orders=False) + trades = Trade.get_trades([Trade.is_open.is_(False)], include_orders=False) # Sell reason exit_reasons = {} for trade in trades: @@ -785,7 +785,8 @@ class RPC: # check if valid pair # check if pair already has an open pair - trade: Trade = Trade.get_trades([Trade.is_open.is_(True), Trade.pair == pair]).first() + trade: Optional[Trade] = Trade.get_trades( + [Trade.is_open.is_(True), Trade.pair == pair]).first() is_short = (order_side == SignalDirection.SHORT) if trade: is_short = trade.is_short diff --git a/freqtrade/rpc/telegram.py b/freqtrade/rpc/telegram.py index 7bbeea2a2..dc92478ab 100644 --- a/freqtrade/rpc/telegram.py +++ b/freqtrade/rpc/telegram.py @@ -1055,10 +1055,14 @@ class Telegram(RPCHandler): query.answer() query.edit_message_text(text="Force exit canceled.") return - trade: Trade = Trade.get_trades(trade_filter=Trade.id == trade_id).first() + trade: Optional[Trade] = Trade.get_trades(trade_filter=Trade.id == trade_id).first() query.answer() - query.edit_message_text(text=f"Manually exiting Trade #{trade_id}, {trade.pair}") - self._force_exit_action(trade_id) + if trade: + query.edit_message_text( + text=f"Manually exiting Trade #{trade_id}, {trade.pair}") + self._force_exit_action(trade_id) + else: + query.edit_message_text(text=f"Trade {trade_id} not found.") def _force_enter_action(self, pair, price: Optional[float], order_side: SignalDirection): if pair != 'cancel': From 764001a4c290ba9bca30a224171f4f88ef20001f Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 21 Feb 2023 06:49:15 +0100 Subject: [PATCH 045/229] Don't reuse variable --- freqtrade/data/btanalysis.py | 2 +- freqtrade/persistence/pairlock_middleware.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/freqtrade/data/btanalysis.py b/freqtrade/data/btanalysis.py index c682436c7..9772506a7 100644 --- a/freqtrade/data/btanalysis.py +++ b/freqtrade/data/btanalysis.py @@ -346,7 +346,7 @@ def evaluate_result_multi(results: pd.DataFrame, timeframe: str, return df_final[df_final['open_trades'] > max_open_trades] -def trade_list_to_dataframe(trades: List[LocalTrade]) -> pd.DataFrame: +def trade_list_to_dataframe(trades: Union[List[Trade], List[LocalTrade]]) -> pd.DataFrame: """ Convert list of Trade objects to pandas Dataframe :param trades: List of trade objects diff --git a/freqtrade/persistence/pairlock_middleware.py b/freqtrade/persistence/pairlock_middleware.py index 4485bb88e..5ed131a9b 100644 --- a/freqtrade/persistence/pairlock_middleware.py +++ b/freqtrade/persistence/pairlock_middleware.py @@ -133,8 +133,8 @@ class PairLocks(): PairLock.query.session.commit() else: # used in backtesting mode; don't show log messages for speed - locks = PairLocks.get_pair_locks(None) - for lock in locks: + locksb = PairLocks.get_pair_locks(None) + for lock in locksb: if lock.reason == reason: lock.active = False From f2f4158974b294339ba3c22352b44c4dd9f31c5d Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 21 Feb 2023 06:58:21 +0100 Subject: [PATCH 046/229] Bump sqlalchemy to 2.0.4 --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 3e6c66757..6b1c888b8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,7 +5,7 @@ pandas-ta==0.3.14b ccxt==2.8.54 cryptography==39.0.1 aiohttp==3.8.4 -SQLAlchemy==2.0.3 +SQLAlchemy==2.0.4 python-telegram-bot==13.15 arrow==1.2.3 cachetools==4.2.2 From d175ab495b39a9a249274b97ea52292840592283 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 28 Feb 2023 07:03:22 +0100 Subject: [PATCH 047/229] Move SessionType to base module --- freqtrade/persistence/base.py | 4 +++- freqtrade/persistence/models.py | 5 ++--- freqtrade/persistence/pairlock.py | 3 +-- freqtrade/persistence/trade_model.py | 3 +-- 4 files changed, 7 insertions(+), 8 deletions(-) diff --git a/freqtrade/persistence/base.py b/freqtrade/persistence/base.py index 2fed715d7..98e483c90 100644 --- a/freqtrade/persistence/base.py +++ b/freqtrade/persistence/base.py @@ -1,6 +1,8 @@ -from sqlalchemy.orm import DeclarativeBase +from sqlalchemy.orm import DeclarativeBase, Session, scoped_session +SessionType = scoped_session[Session] + class ModelBase(DeclarativeBase): pass diff --git a/freqtrade/persistence/models.py b/freqtrade/persistence/models.py index b94be950a..98d1d7a8a 100644 --- a/freqtrade/persistence/models.py +++ b/freqtrade/persistence/models.py @@ -6,11 +6,11 @@ from typing import Any, Dict from sqlalchemy import create_engine, inspect from sqlalchemy.exc import NoSuchModuleError -from sqlalchemy.orm import Session, scoped_session, sessionmaker +from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.pool import StaticPool from freqtrade.exceptions import OperationalException -from freqtrade.persistence.base import ModelBase +from freqtrade.persistence.base import ModelBase, SessionType from freqtrade.persistence.migrations import check_migrate from freqtrade.persistence.pairlock import PairLock from freqtrade.persistence.trade_model import Order, Trade @@ -20,7 +20,6 @@ logger = logging.getLogger(__name__) _SQL_DOCS_URL = 'http://docs.sqlalchemy.org/en/latest/core/engines.html#database-urls' -SessionType = scoped_session[Session] def init_db(db_url: str) -> None: diff --git a/freqtrade/persistence/pairlock.py b/freqtrade/persistence/pairlock.py index b10d74693..d5a8d7ae1 100644 --- a/freqtrade/persistence/pairlock.py +++ b/freqtrade/persistence/pairlock.py @@ -6,8 +6,7 @@ from sqlalchemy.orm import Mapped, Query, mapped_column from sqlalchemy.orm.scoping import _QueryDescriptorType from freqtrade.constants import DATETIME_PRINT_FORMAT -from freqtrade.persistence.base import ModelBase -from freqtrade.persistence.models import SessionType +from freqtrade.persistence.base import ModelBase, SessionType class PairLock(ModelBase): diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 0f85528e0..ce7d56745 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -17,8 +17,7 @@ from freqtrade.enums import ExitType, TradingMode from freqtrade.exceptions import DependencyException, OperationalException from freqtrade.exchange import amount_to_contract_precision, price_to_precision from freqtrade.leverage import interest -from freqtrade.persistence.base import ModelBase -from freqtrade.persistence.models import SessionType +from freqtrade.persistence.base import ModelBase, SessionType from freqtrade.util import FtPrecise From 0f914cf2bd54902ceb96c29499eca888b4422b03 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 28 Feb 2023 07:24:20 +0100 Subject: [PATCH 048/229] Use Mapped for LocalTrade this won't initialize sqlalchemy, as the base class is not inheriting from sqlalchemy. --- freqtrade/persistence/trade_model.py | 108 +++++++++++++-------------- 1 file changed, 54 insertions(+), 54 deletions(-) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index ce7d56745..93701b1ae 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -288,76 +288,76 @@ class LocalTrade(): bt_trades_open_pp: Dict[str, List['LocalTrade']] = defaultdict(list) bt_open_open_trade_count: int = 0 total_profit: float = 0 - realized_profit: float = 0 + realized_profit: Mapped[float] = 0 # type: ignore - id: int = 0 + id: Mapped[int] = 0 # type: ignore - orders: List[Order] = [] + orders: Mapped[List[Order]] = [] # type: ignore - exchange: str = '' - pair: str = '' - base_currency: str = '' - stake_currency: str = '' - is_open: bool = True - fee_open: float = 0.0 - fee_open_cost: Optional[float] = None - fee_open_currency: str = '' - fee_close: float = 0.0 - fee_close_cost: Optional[float] = None - fee_close_currency: str = '' - open_rate: float = 0.0 - open_rate_requested: Optional[float] = None + exchange: Mapped[str] = '' # type: ignore + pair: Mapped[str] = '' # type: ignore + base_currency: Mapped[Optional[str]] = '' # type: ignore + stake_currency: Mapped[Optional[str]] = '' # type: ignore + is_open: Mapped[bool] = True # type: ignore + fee_open: Mapped[float] = 0.0 # type: ignore + fee_open_cost: Mapped[Optional[float]] = None # type: ignore + fee_open_currency: Mapped[Optional[str]] = '' # type: ignore + fee_close: Mapped[Optional[float]] = 0.0 # type: ignore + fee_close_cost: Mapped[Optional[float]] = None # type: ignore + fee_close_currency: Mapped[Optional[str]] = '' # type: ignore + open_rate: Mapped[float] = 0.0 # type: ignore + open_rate_requested: Mapped[Optional[float]] = None # type: ignore # open_trade_value - calculated via _calc_open_trade_value - open_trade_value: float = 0.0 - close_rate: Optional[float] = None - close_rate_requested: Optional[float] = None - close_profit: Optional[float] = None - close_profit_abs: Optional[float] = None - stake_amount: float = 0.0 - max_stake_amount: float = 0.0 - amount: float = 0.0 - amount_requested: Optional[float] = None - open_date: datetime - close_date: Optional[datetime] = None - open_order_id: Optional[str] = None + open_trade_value: Mapped[float] = 0.0 # type: ignore + close_rate: Mapped[Optional[float]] = None # type: ignore + close_rate_requested: Mapped[Optional[float]] = None # type: ignore + close_profit: Mapped[Optional[float]] = None # type: ignore + close_profit_abs: Mapped[Optional[float]] = None # type: ignore + stake_amount: Mapped[float] = 0.0 # type: ignore + max_stake_amount: Mapped[Optional[float]] = 0.0 # type: ignore + amount: Mapped[float] = 0.0 # type: ignore + amount_requested: Mapped[Optional[float]] = None # type: ignore + open_date: Mapped[datetime] + close_date: Mapped[Optional[datetime]] = None # type: ignore + open_order_id: Mapped[Optional[str]] = None # type: ignore # absolute value of the stop loss - stop_loss: float = 0.0 + stop_loss: Mapped[float] = 0.0 # type: ignore # percentage value of the stop loss - stop_loss_pct: float = 0.0 + stop_loss_pct: Mapped[Optional[float]] = 0.0 # type: ignore # absolute value of the initial stop loss - initial_stop_loss: float = 0.0 + initial_stop_loss: Mapped[Optional[float]] = 0.0 # type: ignore # percentage value of the initial stop loss - initial_stop_loss_pct: Optional[float] = None + initial_stop_loss_pct: Mapped[Optional[float]] = None # type: ignore # stoploss order id which is on exchange - stoploss_order_id: Optional[str] = None + stoploss_order_id: Mapped[Optional[str]] = None # type: ignore # last update time of the stoploss order on exchange - stoploss_last_update: Optional[datetime] = None + stoploss_last_update: Mapped[Optional[datetime]] = None # type: ignore # absolute value of the highest reached price - max_rate: float = 0.0 + max_rate: Mapped[Optional[float]] = None # type: ignore # Lowest price reached - min_rate: float = 0.0 - exit_reason: str = '' - exit_order_status: str = '' - strategy: str = '' - enter_tag: Optional[str] = None - timeframe: Optional[int] = None + min_rate: Mapped[Optional[float]] = None # type: ignore + exit_reason: Mapped[Optional[str]] = '' # type: ignore + exit_order_status: Mapped[Optional[str]] = '' # type: ignore + strategy: Mapped[Optional[str]] = '' # type: ignore + enter_tag: Mapped[Optional[str]] = None # type: ignore + timeframe: Mapped[Optional[int]] = None # type: ignore - trading_mode: TradingMode = TradingMode.SPOT - amount_precision: Optional[float] = None - price_precision: Optional[float] = None - precision_mode: Optional[int] = None - contract_size: Optional[float] = None + trading_mode: Mapped[TradingMode] = TradingMode.SPOT # type: ignore + amount_precision: Mapped[Optional[float]] = None # type: ignore + price_precision: Mapped[Optional[float]] = None # type: ignore + precision_mode: Mapped[Optional[int]] = None # type: ignore + contract_size: Mapped[Optional[float]] = None # type: ignore # Leverage trading properties - liquidation_price: Optional[float] = None - is_short: bool = False - leverage: float = 1.0 + liquidation_price: Mapped[Optional[float]] = None # type: ignore + is_short: Mapped[bool] = False # type: ignore + leverage: Mapped[float] = 1.0 # type: ignore # Margin trading properties - interest_rate: float = 0.0 + interest_rate: Mapped[float] = 0.0 # type: ignore # Futures properties - funding_fees: Optional[float] = None + funding_fees: Mapped[Optional[float]] = None # type: ignore @property def stoploss_or_liquidation(self) -> float: @@ -1175,7 +1175,7 @@ class Trade(ModelBase, LocalTrade): """ __tablename__ = 'trades' query: ClassVar[_QueryDescriptorType] - session: ClassVar[SessionType] = None + session: ClassVar[SessionType] use_db: bool = True @@ -1197,7 +1197,7 @@ class Trade(ModelBase, LocalTrade): fee_close_cost: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) fee_close_currency: Mapped[Optional[str]] = mapped_column(String(25), nullable=True) open_rate: Mapped[float] = mapped_column(Float()) - open_rate_requested: Mapped[float] = mapped_column(Float(), nullable=True) + open_rate_requested: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) # open_trade_value - calculated via _calc_open_trade_value open_trade_value = mapped_column(Float()) close_rate: Mapped[Optional[float]] = mapped_column(Float()) @@ -1246,7 +1246,7 @@ class Trade(ModelBase, LocalTrade): liquidation_price: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) # Margin Trading Properties - interest_rate: Mapped[Optional[float]] = mapped_column(Float(), nullable=False, default=0.0) + interest_rate: Mapped[float] = mapped_column(Float(), nullable=False, default=0.0) # Futures properties funding_fees: Mapped[Optional[float]] = mapped_column(Float(), nullable=True, default=None) From 7c09c0178815a725a3ac0df5509e7a0d5100a475 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 28 Feb 2023 07:27:01 +0100 Subject: [PATCH 049/229] Add some more typehints --- freqtrade/persistence/trade_model.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 93701b1ae..887784be3 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -154,7 +154,7 @@ class Order(ModelBase): self.order_update_date = datetime.now(timezone.utc) def to_ccxt_object(self) -> Dict[str, Any]: - order = { + order: Dict[str, Any] = { 'id': self.order_id, 'symbol': self.ft_pair, 'price': self.price, @@ -1062,7 +1062,7 @@ class LocalTrade(): return len(self.select_filled_orders('sell')) @property - def sell_reason(self) -> str: + def sell_reason(self) -> Optional[str]: """ DEPRECATED! Please use exit_reason instead.""" return self.exit_reason @@ -1276,7 +1276,7 @@ class Trade(ModelBase, LocalTrade): def get_trades_proxy(*, pair: Optional[str] = None, is_open: Optional[bool] = None, open_date: Optional[datetime] = None, close_date: Optional[datetime] = None, - ) -> List['LocalTrade']: + ) -> List['LocalTrade', 'Trade']: """ Helper function to query Trades.j Returns a List of trades, filtered on the parameters given. From b5f55c9b145129567d5d642efb7229fbf36c4ff9 Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 1 Mar 2023 06:40:07 +0100 Subject: [PATCH 050/229] Improve type safety in backtesting --- freqtrade/optimize/backtesting.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/freqtrade/optimize/backtesting.py b/freqtrade/optimize/backtesting.py index 7f3036037..1f868f7bf 100644 --- a/freqtrade/optimize/backtesting.py +++ b/freqtrade/optimize/backtesting.py @@ -440,7 +440,8 @@ class Backtesting: side_1 * abs(self.strategy.trailing_stop_positive / leverage))) else: # Worst case: price ticks tiny bit above open and dives down. - stop_rate = row[OPEN_IDX] * (1 - side_1 * abs(trade.stop_loss_pct / leverage)) + stop_rate = row[OPEN_IDX] * (1 - side_1 * abs( + (trade.stop_loss_pct or 0.0) / leverage)) if is_short: assert stop_rate > row[LOW_IDX] else: @@ -472,7 +473,7 @@ class Backtesting: # - (Expected abs profit - open_rate - open_fee) / (fee_close -1) roi_rate = trade.open_rate * roi / leverage open_fee_rate = side_1 * trade.open_rate * (1 + side_1 * trade.fee_open) - close_rate = -(roi_rate + open_fee_rate) / (trade.fee_close - side_1 * 1) + close_rate = -(roi_rate + open_fee_rate) / ((trade.fee_close or 0.0) - side_1 * 1) if is_short: is_new_roi = row[OPEN_IDX] < close_rate else: From e5c9cde36f713c50a7085c7ad4c9377a97bd34b8 Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 1 Mar 2023 07:23:26 +0100 Subject: [PATCH 051/229] Update trades_proxy typing --- freqtrade/persistence/trade_model.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 887784be3..531e86282 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -5,7 +5,7 @@ import logging from collections import defaultdict from datetime import datetime, timedelta, timezone from math import isclose -from typing import Any, ClassVar, Dict, List, Optional +from typing import Any, ClassVar, Dict, List, Optional, cast from sqlalchemy import Enum, Float, ForeignKey, Integer, String, UniqueConstraint, desc, func from sqlalchemy.orm import Mapped, Query, lazyload, mapped_column, relationship @@ -1131,7 +1131,7 @@ class LocalTrade(): @staticmethod def get_open_trades() -> List[Any]: """ - Query trades from persistence layer + Retrieve open trades """ return Trade.get_trades_proxy(is_open=True) @@ -1276,7 +1276,7 @@ class Trade(ModelBase, LocalTrade): def get_trades_proxy(*, pair: Optional[str] = None, is_open: Optional[bool] = None, open_date: Optional[datetime] = None, close_date: Optional[datetime] = None, - ) -> List['LocalTrade', 'Trade']: + ) -> List['LocalTrade']: """ Helper function to query Trades.j Returns a List of trades, filtered on the parameters given. @@ -1295,7 +1295,7 @@ class Trade(ModelBase, LocalTrade): trade_filter.append(Trade.close_date > close_date) if is_open is not None: trade_filter.append(Trade.is_open.is_(is_open)) - return Trade.get_trades(trade_filter).all() + return cast(List[LocalTrade], Trade.get_trades(trade_filter).all()) else: return LocalTrade.get_trades_proxy( pair=pair, is_open=is_open, From a1166b1077ca96db704d97e5d3775d960ee67ba9 Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 1 Mar 2023 07:25:33 +0100 Subject: [PATCH 052/229] allow null fee on calc_base_close --- freqtrade/persistence/trade_model.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 531e86282..7eabfab0f 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -795,10 +795,10 @@ class LocalTrade(): return interest(exchange_name=self.exchange, borrowed=borrowed, rate=rate, hours=hours) - def _calc_base_close(self, amount: FtPrecise, rate: float, fee: float) -> FtPrecise: + def _calc_base_close(self, amount: FtPrecise, rate: float, fee: Optional[float]) -> FtPrecise: close_trade = amount * FtPrecise(rate) - fees = close_trade * FtPrecise(fee) + fees = close_trade * FtPrecise(fee or 0.0) if self.is_short: return close_trade + fees From 4a35d32b6ae84b2c0e372a7e00df283b7df76078 Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 1 Mar 2023 07:26:35 +0100 Subject: [PATCH 053/229] Improve trade stop types --- freqtrade/persistence/trade_model.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 7eabfab0f..d747971fb 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -595,7 +595,7 @@ class LocalTrade(): self.stop_loss_pct = -1 * abs(percent) - def adjust_stop_loss(self, current_price: float, stoploss: float, + def adjust_stop_loss(self, current_price: float, stoploss: Optional[float], initial: bool = False, refresh: bool = False) -> None: """ This adjusts the stop loss to it's most recently observed setting @@ -604,7 +604,7 @@ class LocalTrade(): :param initial: Called to initiate stop_loss. Skips everything if self.stop_loss is already set. """ - if initial and not (self.stop_loss is None or self.stop_loss == 0): + if stoploss is None or (initial and not (self.stop_loss is None or self.stop_loss == 0)): # Don't modify if called with initial and nothing to do return refresh = True if refresh and self.nr_of_successful_entries == 1 else False From 874413ccc59ebe0ab7346de74ea3ff06c82b513c Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 1 Mar 2023 11:16:56 +0000 Subject: [PATCH 054/229] Fix some style violations --- freqtrade/persistence/base.py | 1 + freqtrade/persistence/models.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/freqtrade/persistence/base.py b/freqtrade/persistence/base.py index 98e483c90..fc2dac75e 100644 --- a/freqtrade/persistence/base.py +++ b/freqtrade/persistence/base.py @@ -4,5 +4,6 @@ from sqlalchemy.orm import DeclarativeBase, Session, scoped_session SessionType = scoped_session[Session] + class ModelBase(DeclarativeBase): pass diff --git a/freqtrade/persistence/models.py b/freqtrade/persistence/models.py index 98d1d7a8a..f4058b4eb 100644 --- a/freqtrade/persistence/models.py +++ b/freqtrade/persistence/models.py @@ -10,7 +10,7 @@ from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.pool import StaticPool from freqtrade.exceptions import OperationalException -from freqtrade.persistence.base import ModelBase, SessionType +from freqtrade.persistence.base import ModelBase from freqtrade.persistence.migrations import check_migrate from freqtrade.persistence.pairlock import PairLock from freqtrade.persistence.trade_model import Order, Trade From 388dfec50bbf3ff4884dae25b4edf213a203edf8 Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 1 Mar 2023 18:17:37 +0100 Subject: [PATCH 055/229] Remove last type error --- freqtrade/persistence/trade_model.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index d747971fb..ab7d56766 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -643,7 +643,7 @@ class LocalTrade(): f"initial_stop_loss={self.initial_stop_loss:.8f}, " f"stop_loss={self.stop_loss:.8f}. " f"Trailing stoploss saved us: " - f"{float(self.stop_loss) - float(self.initial_stop_loss):.8f}.") + f"{float(self.stop_loss) - float(self.initial_stop_loss or 0.0):.8f}.") def update_trade(self, order: Order) -> None: """ From f0f72fdd33db951f6bbc24a8e93a6f0acdadafb3 Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 1 Mar 2023 19:48:15 +0100 Subject: [PATCH 056/229] Don't define "mapped" on LocalTrade class --- freqtrade/persistence/trade_model.py | 220 ++++++++++++++------------- 1 file changed, 118 insertions(+), 102 deletions(-) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index ab7d56766..62e2e2a7f 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -288,76 +288,76 @@ class LocalTrade(): bt_trades_open_pp: Dict[str, List['LocalTrade']] = defaultdict(list) bt_open_open_trade_count: int = 0 total_profit: float = 0 - realized_profit: Mapped[float] = 0 # type: ignore + realized_profit: float = 0 - id: Mapped[int] = 0 # type: ignore + id: int = 0 - orders: Mapped[List[Order]] = [] # type: ignore + orders: List[Order] = [] - exchange: Mapped[str] = '' # type: ignore - pair: Mapped[str] = '' # type: ignore - base_currency: Mapped[Optional[str]] = '' # type: ignore - stake_currency: Mapped[Optional[str]] = '' # type: ignore - is_open: Mapped[bool] = True # type: ignore - fee_open: Mapped[float] = 0.0 # type: ignore - fee_open_cost: Mapped[Optional[float]] = None # type: ignore - fee_open_currency: Mapped[Optional[str]] = '' # type: ignore - fee_close: Mapped[Optional[float]] = 0.0 # type: ignore - fee_close_cost: Mapped[Optional[float]] = None # type: ignore - fee_close_currency: Mapped[Optional[str]] = '' # type: ignore - open_rate: Mapped[float] = 0.0 # type: ignore - open_rate_requested: Mapped[Optional[float]] = None # type: ignore + exchange: str = '' + pair: str = '' + base_currency: Optional[str] = '' + stake_currency: Optional[str] = '' + is_open: bool = True + fee_open: float = 0.0 + fee_open_cost: Optional[float] = None + fee_open_currency: Optional[str] = '' + fee_close: Optional[float] = 0.0 + fee_close_cost: Optional[float] = None + fee_close_currency: Optional[str] = '' + open_rate: float = 0.0 + open_rate_requested: Optional[float] = None # open_trade_value - calculated via _calc_open_trade_value - open_trade_value: Mapped[float] = 0.0 # type: ignore - close_rate: Mapped[Optional[float]] = None # type: ignore - close_rate_requested: Mapped[Optional[float]] = None # type: ignore - close_profit: Mapped[Optional[float]] = None # type: ignore - close_profit_abs: Mapped[Optional[float]] = None # type: ignore - stake_amount: Mapped[float] = 0.0 # type: ignore - max_stake_amount: Mapped[Optional[float]] = 0.0 # type: ignore - amount: Mapped[float] = 0.0 # type: ignore - amount_requested: Mapped[Optional[float]] = None # type: ignore - open_date: Mapped[datetime] - close_date: Mapped[Optional[datetime]] = None # type: ignore - open_order_id: Mapped[Optional[str]] = None # type: ignore + open_trade_value: float = 0.0 + close_rate: Optional[float] = None + close_rate_requested: Optional[float] = None + close_profit: Optional[float] = None + close_profit_abs: Optional[float] = None + stake_amount: float = 0.0 + max_stake_amount: Optional[float] = 0.0 + amount: float = 0.0 + amount_requested: Optional[float] = None + open_date: datetime + close_date: Optional[datetime] = None + open_order_id: Optional[str] = None # absolute value of the stop loss - stop_loss: Mapped[float] = 0.0 # type: ignore + stop_loss: float = 0.0 # percentage value of the stop loss - stop_loss_pct: Mapped[Optional[float]] = 0.0 # type: ignore + stop_loss_pct: Optional[float] = 0.0 # absolute value of the initial stop loss - initial_stop_loss: Mapped[Optional[float]] = 0.0 # type: ignore + initial_stop_loss: Optional[float] = 0.0 # percentage value of the initial stop loss - initial_stop_loss_pct: Mapped[Optional[float]] = None # type: ignore + initial_stop_loss_pct: Optional[float] = None # stoploss order id which is on exchange - stoploss_order_id: Mapped[Optional[str]] = None # type: ignore + stoploss_order_id: Optional[str] = None # last update time of the stoploss order on exchange - stoploss_last_update: Mapped[Optional[datetime]] = None # type: ignore + stoploss_last_update: Optional[datetime] = None # absolute value of the highest reached price - max_rate: Mapped[Optional[float]] = None # type: ignore + max_rate: Optional[float] = None # Lowest price reached - min_rate: Mapped[Optional[float]] = None # type: ignore - exit_reason: Mapped[Optional[str]] = '' # type: ignore - exit_order_status: Mapped[Optional[str]] = '' # type: ignore - strategy: Mapped[Optional[str]] = '' # type: ignore - enter_tag: Mapped[Optional[str]] = None # type: ignore - timeframe: Mapped[Optional[int]] = None # type: ignore + min_rate: Optional[float] = None + exit_reason: Optional[str] = '' + exit_order_status: Optional[str] = '' + strategy: Optional[str] = '' + enter_tag: Optional[str] = None + timeframe: Optional[int] = None - trading_mode: Mapped[TradingMode] = TradingMode.SPOT # type: ignore - amount_precision: Mapped[Optional[float]] = None # type: ignore - price_precision: Mapped[Optional[float]] = None # type: ignore - precision_mode: Mapped[Optional[int]] = None # type: ignore - contract_size: Mapped[Optional[float]] = None # type: ignore + trading_mode: TradingMode = TradingMode.SPOT + amount_precision: Optional[float] = None + price_precision: Optional[float] = None + precision_mode: Optional[int] = None + contract_size: Optional[float] = None # Leverage trading properties - liquidation_price: Mapped[Optional[float]] = None # type: ignore - is_short: Mapped[bool] = False # type: ignore - leverage: Mapped[float] = 1.0 # type: ignore + liquidation_price: Optional[float] = None + is_short: bool = False + leverage: float = 1.0 # Margin trading properties - interest_rate: Mapped[float] = 0.0 # type: ignore + interest_rate: float = 0.0 # Futures properties - funding_fees: Mapped[Optional[float]] = None # type: ignore + funding_fees: Optional[float] = None @property def stoploss_or_liquidation(self) -> float: @@ -1179,77 +1179,93 @@ class Trade(ModelBase, LocalTrade): use_db: bool = True - id: Mapped[int] = mapped_column(Integer, primary_key=True) + id: Mapped[int] = mapped_column(Integer, primary_key=True) # type: ignore orders: Mapped[List[Order]] = relationship( "Order", order_by="Order.id", cascade="all, delete-orphan", lazy="selectin", - innerjoin=True) + innerjoin=True) # type: ignore - exchange: Mapped[str] = mapped_column(String(25), nullable=False) - pair: Mapped[str] = mapped_column(String(25), nullable=False, index=True) - base_currency: Mapped[Optional[str]] = mapped_column(String(25), nullable=True) - stake_currency: Mapped[Optional[str]] = mapped_column(String(25), nullable=True) - is_open: Mapped[bool] = mapped_column(nullable=False, default=True, index=True) - fee_open: Mapped[float] = mapped_column(Float(), nullable=False, default=0.0) - fee_open_cost: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) - fee_open_currency: Mapped[Optional[str]] = mapped_column(String(25), nullable=True) - fee_close: Mapped[Optional[float]] = mapped_column(Float(), nullable=False, default=0.0) - fee_close_cost: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) - fee_close_currency: Mapped[Optional[str]] = mapped_column(String(25), nullable=True) - open_rate: Mapped[float] = mapped_column(Float()) - open_rate_requested: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) + exchange: Mapped[str] = mapped_column(String(25), nullable=False) # type: ignore + pair: Mapped[str] = mapped_column(String(25), nullable=False, index=True) # type: ignore + base_currency: Mapped[Optional[str]] = mapped_column(String(25), nullable=True) # type: ignore + stake_currency: Mapped[Optional[str]] = mapped_column(String(25), nullable=True) # type: ignore + is_open: Mapped[bool] = mapped_column(nullable=False, default=True, index=True) # type: ignore + fee_open: Mapped[float] = mapped_column(Float(), nullable=False, default=0.0) # type: ignore + fee_open_cost: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) # type: ignore + fee_open_currency: Mapped[Optional[str]] = mapped_column( + String(25), nullable=True) # type: ignore + fee_close: Mapped[Optional[float]] = mapped_column( + Float(), nullable=False, default=0.0) # type: ignore + fee_close_cost: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) # type: ignore + fee_close_currency: Mapped[Optional[str]] = mapped_column( + String(25), nullable=True) # type: ignore + open_rate: Mapped[float] = mapped_column(Float()) # type: ignore + open_rate_requested: Mapped[Optional[float]] = mapped_column( + Float(), nullable=True) # type: ignore # open_trade_value - calculated via _calc_open_trade_value - open_trade_value = mapped_column(Float()) - close_rate: Mapped[Optional[float]] = mapped_column(Float()) - close_rate_requested: Mapped[Optional[float]] = mapped_column(Float()) - realized_profit: Mapped[float] = mapped_column(Float(), default=0.0) - close_profit: Mapped[Optional[float]] = mapped_column(Float()) - close_profit_abs: Mapped[Optional[float]] = mapped_column(Float()) - stake_amount: Mapped[float] = mapped_column(Float(), nullable=False) - max_stake_amount: Mapped[Optional[float]] = mapped_column(Float()) - amount: Mapped[float] = mapped_column(Float()) - amount_requested: Mapped[Optional[float]] = mapped_column(Float()) - open_date: Mapped[datetime] = mapped_column(nullable=False, default=datetime.utcnow) - close_date: Mapped[Optional[datetime]] = mapped_column() - open_order_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + open_trade_value: Mapped[float] = mapped_column(Float(), nullable=True) # type: ignore + close_rate: Mapped[Optional[float]] = mapped_column(Float()) # type: ignore + close_rate_requested: Mapped[Optional[float]] = mapped_column(Float()) # type: ignore + realized_profit: Mapped[float] = mapped_column( + Float(), default=0.0, nullable=True) # type: ignore + close_profit: Mapped[Optional[float]] = mapped_column(Float()) # type: ignore + close_profit_abs: Mapped[Optional[float]] = mapped_column(Float()) # type: ignore + stake_amount: Mapped[float] = mapped_column(Float(), nullable=False) # type: ignore + max_stake_amount: Mapped[Optional[float]] = mapped_column(Float()) # type: ignore + amount: Mapped[float] = mapped_column(Float()) # type: ignore + amount_requested: Mapped[Optional[float]] = mapped_column(Float()) # type: ignore + open_date: Mapped[datetime] = mapped_column( + nullable=False, default=datetime.utcnow) # type: ignore + close_date: Mapped[Optional[datetime]] = mapped_column() # type: ignore + open_order_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) # type: ignore # absolute value of the stop loss - stop_loss: Mapped[float] = mapped_column(Float(), nullable=True, default=0.0) + stop_loss: Mapped[float] = mapped_column(Float(), nullable=True, default=0.0) # type: ignore # percentage value of the stop loss - stop_loss_pct: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) + stop_loss_pct: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) # type: ignore # absolute value of the initial stop loss - initial_stop_loss: Mapped[Optional[float]] = mapped_column(Float(), nullable=True, default=0.0) + initial_stop_loss: Mapped[Optional[float]] = mapped_column( + Float(), nullable=True, default=0.0) # type: ignore # percentage value of the initial stop loss - initial_stop_loss_pct: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) + initial_stop_loss_pct: Mapped[Optional[float]] = mapped_column( + Float(), nullable=True) # type: ignore # stoploss order id which is on exchange - stoploss_order_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True, index=True) + stoploss_order_id: Mapped[Optional[str]] = mapped_column( + String(255), nullable=True, index=True) # type: ignore # last update time of the stoploss order on exchange - stoploss_last_update: Mapped[Optional[datetime]] = mapped_column(nullable=True) + stoploss_last_update: Mapped[Optional[datetime]] = mapped_column(nullable=True) # type: ignore # absolute value of the highest reached price - max_rate: Mapped[Optional[float]] = mapped_column(Float(), nullable=True, default=0.0) + max_rate: Mapped[Optional[float]] = mapped_column( + Float(), nullable=True, default=0.0) # type: ignore # Lowest price reached - min_rate: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) - exit_reason: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) - exit_order_status: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) - strategy: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) - enter_tag: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) - timeframe: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + min_rate: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) # type: ignore + exit_reason: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) # type: ignore + exit_order_status: Mapped[Optional[str]] = mapped_column( + String(100), nullable=True) # type: ignore + strategy: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) # type: ignore + enter_tag: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) # type: ignore + timeframe: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) # type: ignore - trading_mode: Mapped[TradingMode] = mapped_column(Enum(TradingMode), nullable=True) - amount_precision: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) - price_precision: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) - precision_mode: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) - contract_size: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) + trading_mode: Mapped[TradingMode] = mapped_column( + Enum(TradingMode), nullable=True) # type: ignore + amount_precision: Mapped[Optional[float]] = mapped_column( + Float(), nullable=True) # type: ignore + price_precision: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) # type: ignore + precision_mode: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) # type: ignore + contract_size: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) # type: ignore # Leverage trading properties - leverage: Mapped[float] = mapped_column(Float(), nullable=True, default=1.0) - is_short: Mapped[bool] = mapped_column(nullable=False, default=False) - liquidation_price: Mapped[Optional[float]] = mapped_column(Float(), nullable=True) + leverage: Mapped[float] = mapped_column(Float(), nullable=True, default=1.0) # type: ignore + is_short: Mapped[bool] = mapped_column(nullable=False, default=False) # type: ignore + liquidation_price: Mapped[Optional[float]] = mapped_column( + Float(), nullable=True) # type: ignore # Margin Trading Properties - interest_rate: Mapped[float] = mapped_column(Float(), nullable=False, default=0.0) + interest_rate: Mapped[float] = mapped_column( + Float(), nullable=False, default=0.0) # type: ignore # Futures properties - funding_fees: Mapped[Optional[float]] = mapped_column(Float(), nullable=True, default=None) + funding_fees: Mapped[Optional[float]] = mapped_column( + Float(), nullable=True, default=None) # type: ignore def __init__(self, **kwargs): super().__init__(**kwargs) From 59d57d34667524e3eeed404fbfb0e3c62b4faa3b Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 1 Mar 2023 20:01:43 +0100 Subject: [PATCH 057/229] Improve test resiliance --- tests/test_freqtradebot.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/test_freqtradebot.py b/tests/test_freqtradebot.py index 1ea3ebfc6..800e76342 100644 --- a/tests/test_freqtradebot.py +++ b/tests/test_freqtradebot.py @@ -3036,6 +3036,7 @@ def test_handle_cancel_enter(mocker, caplog, default_conf_usdt, limit_order, is_ # Order remained open for some reason (cancel failed) cancel_buy_order['status'] = 'open' cancel_order_mock = MagicMock(return_value=cancel_buy_order) + trade.open_order_id = 'some_open_order' mocker.patch(f'{EXMS}.cancel_order_with_result', cancel_order_mock) assert not freqtrade.handle_cancel_enter(trade, l_order, reason) assert log_has_re(r"Order .* for .* not cancelled.", caplog) @@ -3231,6 +3232,7 @@ def test_handle_cancel_exit_cancel_exception(mocker, default_conf_usdt) -> None: trade = MagicMock() reason = CANCEL_REASON['TIMEOUT'] order = {'remaining': 1, + 'id': '125', 'amount': 1, 'status': "open"} assert not freqtrade.handle_cancel_exit(trade, order, reason) From b4b8dde4fb9a0646297c17af8175f5f1cc3d70af Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 1 Mar 2023 20:41:49 +0100 Subject: [PATCH 058/229] Add sqlalchemy to pre-commit dependencies --- .pre-commit-config.yaml | 1 + build_helpers/pre_commit_update.py | 7 ++++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 05f4df92b..acc0c8a17 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -18,6 +18,7 @@ repos: - types-requests==2.28.11.15 - types-tabulate==0.9.0.1 - types-python-dateutil==2.8.19.9 + - SQLAlchemy==2.0.4 # stages: [push] - repo: https://github.com/pycqa/isort diff --git a/build_helpers/pre_commit_update.py b/build_helpers/pre_commit_update.py index 8724d8ade..e6b47d100 100644 --- a/build_helpers/pre_commit_update.py +++ b/build_helpers/pre_commit_update.py @@ -8,12 +8,17 @@ import yaml pre_commit_file = Path('.pre-commit-config.yaml') require_dev = Path('requirements-dev.txt') +require = Path('requirements.txt') with require_dev.open('r') as rfile: requirements = rfile.readlines() +with require.open('r') as rfile: + requirements.extend(rfile.readlines()) + # Extract types only -type_reqs = [r.strip('\n') for r in requirements if r.startswith('types-')] +type_reqs = [r.strip('\n') for r in requirements if r.startswith( + 'types-') or r.startswith('SQLAlchemy')] with pre_commit_file.open('r') as file: f = yaml.load(file, Loader=yaml.FullLoader) From b980f45b2b3bbb5ef1b381af9708694f9d1685d3 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 2 Mar 2023 06:23:01 +0100 Subject: [PATCH 059/229] Fix test mypy errors --- freqtrade/persistence/trade_model.py | 4 ++++ .../strats/broken_strats/broken_futures_strategies.py | 5 +++-- tests/strategy/strats/strategy_test_v3.py | 2 +- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 62e2e2a7f..a05eb7409 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -99,6 +99,10 @@ class Order(ModelBase): def safe_filled(self) -> float: return self.filled if self.filled is not None else self.amount or 0.0 + @property + def safe_cost(self) -> float: + return self.cost or 0.0 + @property def safe_remaining(self) -> float: return ( diff --git a/tests/strategy/strats/broken_strats/broken_futures_strategies.py b/tests/strategy/strats/broken_strats/broken_futures_strategies.py index 7e6955d37..bb7ce2b32 100644 --- a/tests/strategy/strats/broken_strats/broken_futures_strategies.py +++ b/tests/strategy/strats/broken_strats/broken_futures_strategies.py @@ -7,6 +7,7 @@ from datetime import datetime from pandas import DataFrame +from freqtrade.persistence.trade_model import Order from freqtrade.strategy.interface import IStrategy @@ -35,7 +36,7 @@ class TestStrategyImplementBuyTimeout(TestStrategyNoImplementSell): def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: return super().populate_exit_trend(dataframe, metadata) - def check_buy_timeout(self, pair: str, trade, order: dict, + def check_buy_timeout(self, pair: str, trade, order: Order, current_time: datetime, **kwargs) -> bool: return False @@ -44,6 +45,6 @@ class TestStrategyImplementSellTimeout(TestStrategyNoImplementSell): def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: return super().populate_exit_trend(dataframe, metadata) - def check_sell_timeout(self, pair: str, trade, order: dict, + def check_sell_timeout(self, pair: str, trade, order: Order, current_time: datetime, **kwargs) -> bool: return False diff --git a/tests/strategy/strats/strategy_test_v3.py b/tests/strategy/strats/strategy_test_v3.py index 6f5ff573b..2d5121403 100644 --- a/tests/strategy/strats/strategy_test_v3.py +++ b/tests/strategy/strats/strategy_test_v3.py @@ -197,7 +197,7 @@ class StrategyTestV3(IStrategy): if current_profit < -0.0075: orders = trade.select_filled_orders(trade.entry_side) - return round(orders[0].cost, 0) + return round(orders[0].safe_cost, 0) return None From 8103656ae17e4e851584f2f9146491faf7529bf9 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 2 Mar 2023 06:36:03 +0100 Subject: [PATCH 060/229] Bump mypy in pre-commit --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index acc0c8a17..565eb96f7 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -8,7 +8,7 @@ repos: # stages: [push] - repo: https://github.com/pre-commit/mirrors-mypy - rev: "v0.991" + rev: "v1.0.1" hooks: - id: mypy exclude: build_helpers From 103bd9e2f217bbf277153f9f0fb63f25b30246d0 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 2 Mar 2023 06:55:33 +0100 Subject: [PATCH 061/229] keep Trade.session private --- freqtrade/commands/db_commands.py | 2 +- freqtrade/persistence/models.py | 12 ++++++------ freqtrade/persistence/pairlock.py | 2 +- freqtrade/persistence/trade_model.py | 4 ++-- tests/persistence/test_migrations.py | 6 +++--- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/freqtrade/commands/db_commands.py b/freqtrade/commands/db_commands.py index b4997582d..c424016b1 100644 --- a/freqtrade/commands/db_commands.py +++ b/freqtrade/commands/db_commands.py @@ -20,7 +20,7 @@ def start_convert_db(args: Dict[str, Any]) -> None: config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE) init_db(config['db_url']) - session_target = Trade.session + session_target = Trade._session init_db(config['db_url_from']) logger.info("Starting db migration.") diff --git a/freqtrade/persistence/models.py b/freqtrade/persistence/models.py index f4058b4eb..d718af2f4 100644 --- a/freqtrade/persistence/models.py +++ b/freqtrade/persistence/models.py @@ -54,12 +54,12 @@ def init_db(db_url: str) -> None: # https://docs.sqlalchemy.org/en/13/orm/contextual.html#thread-local-scope # Scoped sessions proxy requests to the appropriate thread-local session. # We should use the scoped_session object - not a seperately initialized version - Trade.session = scoped_session(sessionmaker(bind=engine, autoflush=False)) - Order.session = Trade.session - PairLock.session = Trade.session - Trade.query = Trade.session.query_property() - Order.query = Trade.session.query_property() - PairLock.query = Trade.session.query_property() + Trade._session = scoped_session(sessionmaker(bind=engine, autoflush=False)) + Order._session = Trade._session + PairLock._session = Trade._session + Trade.query = Trade._session.query_property() + Order.query = Trade._session.query_property() + PairLock.query = Trade._session.query_property() previous_tables = inspect(engine).get_table_names() ModelBase.metadata.create_all(engine) diff --git a/freqtrade/persistence/pairlock.py b/freqtrade/persistence/pairlock.py index d5a8d7ae1..a6d1eeaf0 100644 --- a/freqtrade/persistence/pairlock.py +++ b/freqtrade/persistence/pairlock.py @@ -15,7 +15,7 @@ class PairLock(ModelBase): """ __tablename__ = 'pairlocks' query: ClassVar[_QueryDescriptorType] - session: ClassVar[SessionType] + _session: ClassVar[SessionType] id: Mapped[int] = mapped_column(primary_key=True) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index a05eb7409..0ae5fba25 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -37,7 +37,7 @@ class Order(ModelBase): """ __tablename__ = 'orders' query: ClassVar[_QueryDescriptorType] - session: ClassVar[SessionType] + _session: ClassVar[SessionType] # Uniqueness should be ensured over pair, order_id # its likely that order_id is unique per Pair on some exchanges. @@ -1179,7 +1179,7 @@ class Trade(ModelBase, LocalTrade): """ __tablename__ = 'trades' query: ClassVar[_QueryDescriptorType] - session: ClassVar[SessionType] + _session: ClassVar[SessionType] use_db: bool = True diff --git a/tests/persistence/test_migrations.py b/tests/persistence/test_migrations.py index 5254164c1..2a6959d58 100644 --- a/tests/persistence/test_migrations.py +++ b/tests/persistence/test_migrations.py @@ -21,8 +21,8 @@ spot, margin, futures = TradingMode.SPOT, TradingMode.MARGIN, TradingMode.FUTURE def test_init_create_session(default_conf): # Check if init create a session init_db(default_conf['db_url']) - assert hasattr(Trade, 'session') - assert 'scoped_session' in type(Trade.session).__name__ + assert hasattr(Trade, '_session') + assert 'scoped_session' in type(Trade._session).__name__ def test_init_custom_db_url(default_conf, tmpdir): @@ -34,7 +34,7 @@ def test_init_custom_db_url(default_conf, tmpdir): init_db(default_conf['db_url']) assert Path(filename).is_file() - r = Trade.session.execute(text("PRAGMA journal_mode")) + r = Trade._session.execute(text("PRAGMA journal_mode")) assert r.first() == ('wal',) From 49bfa556bfa413833fbb59b6bde2e3de6de9f65f Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 25 Oct 2022 21:04:40 +0200 Subject: [PATCH 062/229] Update CI to test against python 3.11 --- .github/workflows/ci.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 17c0efd6d..191a10d1c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,7 +24,7 @@ jobs: strategy: matrix: os: [ ubuntu-20.04, ubuntu-22.04 ] - python-version: ["3.8", "3.9", "3.10"] + python-version: ["3.8", "3.9", "3.10", "3.11"] steps: - uses: actions/checkout@v3 @@ -115,7 +115,7 @@ jobs: strategy: matrix: os: [ macos-latest ] - python-version: ["3.8", "3.9", "3.10"] + python-version: ["3.8", "3.9", "3.10", "3.11"] steps: - uses: actions/checkout@v3 @@ -212,7 +212,7 @@ jobs: strategy: matrix: os: [ windows-latest ] - python-version: ["3.8", "3.9", "3.10"] + python-version: ["3.8", "3.9", "3.10", "3.11"] steps: - uses: actions/checkout@v3 From 684d310ea0d7c05996fe08b6e509cc1d6771c61e Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 25 Feb 2023 13:20:26 +0100 Subject: [PATCH 063/229] Limit catboost to python <3.11 --- requirements-freqai.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-freqai.txt b/requirements-freqai.txt index 5b27ecf95..bc0be85e5 100644 --- a/requirements-freqai.txt +++ b/requirements-freqai.txt @@ -5,7 +5,7 @@ # Required for freqai scikit-learn==1.1.3 joblib==1.2.0 -catboost==1.1.1; platform_machine != 'aarch64' +catboost==1.1.1; platform_machine != 'aarch64' and python_version < '3.11' lightgbm==3.3.5 xgboost==1.7.4 tensorboard==2.12.0 From 7a7f16b6589fc2b36ceb0bd17651405bb8f5a4ce Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 25 Feb 2023 13:27:28 +0100 Subject: [PATCH 064/229] Skip catboost tests on py3.11 --- tests/freqai/test_freqai_interface.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/tests/freqai/test_freqai_interface.py b/tests/freqai/test_freqai_interface.py index cdfc943af..7d229434f 100644 --- a/tests/freqai/test_freqai_interface.py +++ b/tests/freqai/test_freqai_interface.py @@ -1,5 +1,6 @@ import platform import shutil +import sys from pathlib import Path from unittest.mock import MagicMock @@ -17,6 +18,10 @@ from tests.conftest import EXMS, create_mock_trades, get_patched_exchange, log_h from tests.freqai.conftest import get_patched_freqai_strategy, make_rl_config +def is_py11() -> bool: + return sys.version_info >= (3, 11) + + def is_arm() -> bool: machine = platform.machine() return "arm" in machine or "aarch64" in machine @@ -41,7 +46,7 @@ def is_mac() -> bool: def test_extract_data_and_train_model_Standard(mocker, freqai_conf, model, pca, dbscan, float32, can_short, shuffle, buffer): - if is_arm() and model == 'CatboostRegressor': + if (is_arm() or is_py11()) and model == 'CatboostRegressor': pytest.skip("CatBoost is not supported on ARM") if is_mac() and not is_arm() and 'Reinforcement' in model: @@ -117,7 +122,7 @@ def test_extract_data_and_train_model_Standard(mocker, freqai_conf, model, pca, ('CatboostClassifierMultiTarget', "freqai_test_multimodel_classifier_strat") ]) def test_extract_data_and_train_model_MultiTargets(mocker, freqai_conf, model, strat): - if is_arm() and 'Catboost' in model: + if (is_arm() or is_py11()) and 'Catboost' in model: pytest.skip("CatBoost is not supported on ARM") freqai_conf.update({"timerange": "20180110-20180130"}) @@ -159,7 +164,7 @@ def test_extract_data_and_train_model_MultiTargets(mocker, freqai_conf, model, s 'XGBoostRFClassifier', ]) def test_extract_data_and_train_model_Classifiers(mocker, freqai_conf, model): - if is_arm() and model == 'CatboostClassifier': + if (is_arm() or is_py11()) and model == 'CatboostClassifier': pytest.skip("CatBoost is not supported on ARM") freqai_conf.update({"freqaimodel": model}) @@ -208,7 +213,7 @@ def test_extract_data_and_train_model_Classifiers(mocker, freqai_conf, model): def test_start_backtesting(mocker, freqai_conf, model, num_files, strat, caplog): freqai_conf.get("freqai", {}).update({"save_backtest_models": True}) freqai_conf['runmode'] = RunMode.BACKTEST - if is_arm() and "Catboost" in model: + if (is_arm() or is_py11()) and "Catboost" in model: pytest.skip("CatBoost is not supported on ARM") if is_mac() and 'Reinforcement' in model: From b1a5776f1480461f87403e136df4eb591a3b0c97 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 25 Feb 2023 15:21:12 +0100 Subject: [PATCH 065/229] Skip reinforcement learning for python 3.11 --- requirements-freqai-rl.txt | 8 ++++---- tests/freqai/test_freqai_interface.py | 7 ++++++- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/requirements-freqai-rl.txt b/requirements-freqai-rl.txt index c242af43e..4de7d8fab 100644 --- a/requirements-freqai-rl.txt +++ b/requirements-freqai-rl.txt @@ -2,9 +2,9 @@ -r requirements-freqai.txt # Required for freqai-rl -torch==1.13.1 -stable-baselines3==1.7.0 -sb3-contrib==1.7.0 +torch==1.13.1; python_version < '3.11' +stable-baselines3==1.7.0; python_version < '3.11' +sb3-contrib==1.7.0; python_version < '3.11' # Gym is forced to this version by stable-baselines3. setuptools==65.5.1 # Should be removed when gym is fixed. -gym==0.21 +gym==0.21; python_version < '3.11' diff --git a/tests/freqai/test_freqai_interface.py b/tests/freqai/test_freqai_interface.py index 7d229434f..0584ed9f5 100644 --- a/tests/freqai/test_freqai_interface.py +++ b/tests/freqai/test_freqai_interface.py @@ -51,7 +51,8 @@ def test_extract_data_and_train_model_Standard(mocker, freqai_conf, model, pca, if is_mac() and not is_arm() and 'Reinforcement' in model: pytest.skip("Reinforcement learning module not available on intel based Mac OS") - + if is_py11() and 'Reinforcement' in model: + pytest.skip("Reinforcement learning currently not available on python 3.11.") model_save_ext = 'joblib' freqai_conf.update({"freqaimodel": model}) freqai_conf.update({"timerange": "20180110-20180130"}) @@ -218,6 +219,8 @@ def test_start_backtesting(mocker, freqai_conf, model, num_files, strat, caplog) if is_mac() and 'Reinforcement' in model: pytest.skip("Reinforcement learning module not available on intel based Mac OS") + if is_py11() and 'Reinforcement' in model: + pytest.skip("Reinforcement learning currently not available on python 3.11.") Trade.use_db = False freqai_conf.update({"freqaimodel": model}) @@ -514,6 +517,8 @@ def test_get_state_info(mocker, freqai_conf, dp_exists, caplog, tickers): if is_mac(): pytest.skip("Reinforcement learning module not available on intel based Mac OS") + if is_py11(): + pytest.skip("Reinforcement learning currently not available on python 3.11.") freqai_conf.update({"freqaimodel": "ReinforcementLearner"}) freqai_conf.update({"timerange": "20180110-20180130"}) From 38050b5346fa563e9592bdb3258602adb1b753c1 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 25 Feb 2023 15:25:47 +0100 Subject: [PATCH 066/229] Simplify "model-run" conditions --- tests/freqai/test_freqai_interface.py | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/tests/freqai/test_freqai_interface.py b/tests/freqai/test_freqai_interface.py index 0584ed9f5..f8bee3659 100644 --- a/tests/freqai/test_freqai_interface.py +++ b/tests/freqai/test_freqai_interface.py @@ -32,6 +32,17 @@ def is_mac() -> bool: return "Darwin" in machine +def can_run_model(model: str) -> None: + if (is_arm() or is_py11()) and "Catboost" in model: + pytest.skip("CatBoost is not supported on ARM") + + if is_mac() and not is_arm() and 'Reinforcement' in model: + pytest.skip("Reinforcement learning module not available on intel based Mac OS") + + if is_py11() and 'Reinforcement' in model: + pytest.skip("Reinforcement learning currently not available on python 3.11.") + + @pytest.mark.parametrize('model, pca, dbscan, float32, can_short, shuffle, buffer', [ ('LightGBMRegressor', True, False, True, True, False, 0), ('XGBoostRegressor', False, True, False, True, False, 10), @@ -46,13 +57,7 @@ def is_mac() -> bool: def test_extract_data_and_train_model_Standard(mocker, freqai_conf, model, pca, dbscan, float32, can_short, shuffle, buffer): - if (is_arm() or is_py11()) and model == 'CatboostRegressor': - pytest.skip("CatBoost is not supported on ARM") - - if is_mac() and not is_arm() and 'Reinforcement' in model: - pytest.skip("Reinforcement learning module not available on intel based Mac OS") - if is_py11() and 'Reinforcement' in model: - pytest.skip("Reinforcement learning currently not available on python 3.11.") + can_run_model(model) model_save_ext = 'joblib' freqai_conf.update({"freqaimodel": model}) freqai_conf.update({"timerange": "20180110-20180130"}) @@ -212,15 +217,11 @@ def test_extract_data_and_train_model_Classifiers(mocker, freqai_conf, model): ], ) def test_start_backtesting(mocker, freqai_conf, model, num_files, strat, caplog): + can_run_model(model) + freqai_conf.get("freqai", {}).update({"save_backtest_models": True}) freqai_conf['runmode'] = RunMode.BACKTEST - if (is_arm() or is_py11()) and "Catboost" in model: - pytest.skip("CatBoost is not supported on ARM") - if is_mac() and 'Reinforcement' in model: - pytest.skip("Reinforcement learning module not available on intel based Mac OS") - if is_py11() and 'Reinforcement' in model: - pytest.skip("Reinforcement learning currently not available on python 3.11.") Trade.use_db = False freqai_conf.update({"freqaimodel": model}) From 5d0e14b5644d100ed2a5fe7ddcc6b987cbc69741 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 2 Mar 2023 07:07:09 +0100 Subject: [PATCH 067/229] Don't mock full modules --- tests/rpc/test_rpc_apiserver.py | 4 ++-- tests/rpc/test_rpc_telegram.py | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index b104ec854..f898dd476 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -1179,7 +1179,7 @@ def test_api_force_entry(botclient, mocker, fee, endpoint): ftbot.config['force_entry_enable'] = True fbuy_mock = MagicMock(return_value=None) - mocker.patch("freqtrade.rpc.RPC._rpc_force_entry", fbuy_mock) + mocker.patch("freqtrade.rpc.rpc.RPC._rpc_force_entry", fbuy_mock) rc = client_post(client, f"{BASE_URI}/{endpoint}", data={"pair": "ETH/BTC"}) assert_response(rc) @@ -1205,7 +1205,7 @@ def test_api_force_entry(botclient, mocker, fee, endpoint): strategy=CURRENT_TEST_STRATEGY, trading_mode=TradingMode.SPOT )) - mocker.patch("freqtrade.rpc.RPC._rpc_force_entry", fbuy_mock) + mocker.patch("freqtrade.rpc.rpc.RPC._rpc_force_entry", fbuy_mock) rc = client_post(client, f"{BASE_URI}/{endpoint}", data={"pair": "ETH/BTC"}) diff --git a/tests/rpc/test_rpc_telegram.py b/tests/rpc/test_rpc_telegram.py index 3e1421cb5..7b3411113 100644 --- a/tests/rpc/test_rpc_telegram.py +++ b/tests/rpc/test_rpc_telegram.py @@ -1209,7 +1209,7 @@ def test_force_enter_handle(default_conf, update, mocker) -> None: mocker.patch('freqtrade.rpc.rpc.CryptoToFiatConverter._find_price', return_value=15000.0) fbuy_mock = MagicMock(return_value=None) - mocker.patch('freqtrade.rpc.RPC._rpc_force_entry', fbuy_mock) + mocker.patch('freqtrade.rpc.rpc.RPC._rpc_force_entry', fbuy_mock) telegram, freqtradebot, _ = get_telegram_testobject(mocker, default_conf) patch_get_signal(freqtradebot) @@ -1226,7 +1226,7 @@ def test_force_enter_handle(default_conf, update, mocker) -> None: # Reset and retry with specified price fbuy_mock = MagicMock(return_value=None) - mocker.patch('freqtrade.rpc.RPC._rpc_force_entry', fbuy_mock) + mocker.patch('freqtrade.rpc.rpc.RPC._rpc_force_entry', fbuy_mock) # /forcelong ETH/BTC 0.055 context = MagicMock() context.args = ["ETH/BTC", "0.055"] @@ -1255,7 +1255,7 @@ def test_force_enter_no_pair(default_conf, update, mocker) -> None: mocker.patch('freqtrade.rpc.rpc.CryptoToFiatConverter._find_price', return_value=15000.0) fbuy_mock = MagicMock(return_value=None) - mocker.patch('freqtrade.rpc.RPC._rpc_force_entry', fbuy_mock) + mocker.patch('freqtrade.rpc.rpc.RPC._rpc_force_entry', fbuy_mock) telegram, freqtradebot, msg_mock = get_telegram_testobject(mocker, default_conf) From 5b0c1437130a502f322e915a4095b43e68ba88b2 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 2 Mar 2023 19:29:41 +0100 Subject: [PATCH 068/229] Update some comments about 3.11 --- docs/freqai.md | 4 ++++ docs/windows_installation.md | 2 +- setup.cfg | 1 + 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/freqai.md b/docs/freqai.md index 5c6b5b2ce..ef8efb840 100644 --- a/docs/freqai.md +++ b/docs/freqai.md @@ -71,6 +71,10 @@ pip install -r requirements-freqai.txt !!! Note Catboost will not be installed on arm devices (raspberry, Mac M1, ARM based VPS, ...), since it does not provide wheels for this platform. +!!! Note "python 3.11" + Some dependencies (Catboost, Torch) currently don't support python 3.11. Freqtrade therefore only supports python 3.10 for these models/dependencies. + Tests involving these dependencies are skipped on 3.11. + ### Usage with docker If you are using docker, a dedicated tag with FreqAI dependencies is available as `:freqai`. As such - you can replace the image line in your docker compose file with `image: freqtradeorg/freqtrade:develop_freqai`. This image contains the regular FreqAI dependencies. Similar to native installs, Catboost will not be available on ARM based devices. diff --git a/docs/windows_installation.md b/docs/windows_installation.md index 1b0d9d724..43d6728ee 100644 --- a/docs/windows_installation.md +++ b/docs/windows_installation.md @@ -26,7 +26,7 @@ Install ta-lib according to the [ta-lib documentation](https://github.com/mrjbq7 As compiling from source on windows has heavy dependencies (requires a partial visual studio installation), there is also a repository of unofficial pre-compiled windows Wheels [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib), which need to be downloaded and installed using `pip install TA_Lib-0.4.25-cp38-cp38-win_amd64.whl` (make sure to use the version matching your python version). -Freqtrade provides these dependencies for the latest 3 Python versions (3.8, 3.9 and 3.10) and for 64bit Windows. +Freqtrade provides these dependencies for the latest 3 Python versions (3.8, 3.9, 3.10 and 3.11) and for 64bit Windows. Other versions must be downloaded from the above link. ``` powershell diff --git a/setup.cfg b/setup.cfg index 60ec8a75f..b54b62619 100644 --- a/setup.cfg +++ b/setup.cfg @@ -17,6 +17,7 @@ classifiers = Programming Language :: Python :: 3.8 Programming Language :: Python :: 3.9 Programming Language :: Python :: 3.10 + Programming Language :: Python :: 3.11 Operating System :: MacOS Operating System :: Unix Topic :: Office/Business :: Financial :: Investment From 022f85095e2100901d1457d1014fc879ae033843 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 2 Mar 2023 19:50:01 +0100 Subject: [PATCH 069/229] Show Number of exits part of #8234 --- freqtrade/rpc/telegram.py | 3 +++ tests/rpc/test_rpc_telegram.py | 1 + 2 files changed, 4 insertions(+) diff --git a/freqtrade/rpc/telegram.py b/freqtrade/rpc/telegram.py index dc92478ab..6f82a7316 100644 --- a/freqtrade/rpc/telegram.py +++ b/freqtrade/rpc/telegram.py @@ -561,6 +561,8 @@ class Telegram(RPCHandler): for r in results: r['open_date_hum'] = arrow.get(r['open_date']).humanize() r['num_entries'] = len([o for o in r['orders'] if o['ft_is_entry']]) + r['num_exits'] = len([o for o in r['orders'] if not o['ft_is_entry'] + and not o['ft_order_side'] == 'stoploss']) r['exit_reason'] = r.get('exit_reason', "") r['stake_amount_r'] = round_coin_value(r['stake_amount'], r['quote_currency']) r['profit_abs_r'] = round_coin_value(r['profit_abs'], r['quote_currency']) @@ -581,6 +583,7 @@ class Telegram(RPCHandler): if position_adjust: max_buy_str = (f"/{max_entries + 1}" if (max_entries > 0) else "") lines.append("*Number of Entries:* `{num_entries}`" + max_buy_str) + lines.append("*Number of Exits:* `{num_exits}`") lines.extend([ "*Open Rate:* `{open_rate:.8f}`", diff --git a/tests/rpc/test_rpc_telegram.py b/tests/rpc/test_rpc_telegram.py index 7b3411113..26cb93821 100644 --- a/tests/rpc/test_rpc_telegram.py +++ b/tests/rpc/test_rpc_telegram.py @@ -279,6 +279,7 @@ def test_telegram_status_multi_entry(default_conf, update, mocker, fee) -> None: assert msg_mock.call_count == 4 msg = msg_mock.call_args_list[0][0][0] assert re.search(r'Number of Entries.*2', msg) + assert re.search(r'Number of Exits.*0', msg) assert re.search(r'Average Entry Price', msg) assert re.search(r'Order filled', msg) assert re.search(r'Close Date:', msg) is None From 9573974c4798982a87c9e70a7a341ac4235ba956 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 3 Mar 2023 06:36:35 +0100 Subject: [PATCH 070/229] Update deprecations document --- docs/deprecated.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/deprecated.md b/docs/deprecated.md index 3b5b28b81..6719ce56d 100644 --- a/docs/deprecated.md +++ b/docs/deprecated.md @@ -74,3 +74,8 @@ Webhook terminology changed from "sell" to "exit", and from "buy" to "entry", re * `webhooksell`, `webhookexit` -> `exit` * `webhooksellfill`, `webhookexitfill` -> `exit_fill` * `webhooksellcancel`, `webhookexitcancel` -> `exit_cancel` + + +## Removal of `populate_any_indicators` + +version 2023.3 saw the removal of `populate_any_indicators` in favor of split methods for feature engineering and targets. Please read the [migration document](strategy_migration.md#freqai-strategy) for full details. From c03c3a57066ef20833174bdd95a3367b405ed696 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 3 Mar 2023 18:12:41 +0100 Subject: [PATCH 071/229] improve order REPR display --- freqtrade/persistence/trade_model.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 0ae5fba25..1c37635f0 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -120,8 +120,9 @@ class Order(ModelBase): def __repr__(self): - return (f'Order(id={self.id}, order_id={self.order_id}, trade_id={self.ft_trade_id}, ' - f'side={self.side}, order_type={self.order_type}, status={self.status})') + return (f"Order(id={self.id}, order_id={self.order_id}, trade_id={self.ft_trade_id}, " + f"side={self.side}, filled={self.safe_filled}, price={self.safe_price}, " + f"order_type={self.order_type}, status={self.status})") def update_from_ccxt_object(self, order): """ From 87b75134016ed748b5d6732a21fc7ca053ca2631 Mon Sep 17 00:00:00 2001 From: hippocritical Date: Fri, 3 Mar 2023 18:53:09 +0100 Subject: [PATCH 072/229] fixed --strategy-list moved ast comments to requirements.txt >=1.0.0 (since that is the first version that adds the comments unparsing) --- freqtrade/commands/strategy_utils_commands.py | 2 +- requirements.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/freqtrade/commands/strategy_utils_commands.py b/freqtrade/commands/strategy_utils_commands.py index dc94f2b67..0124b73b6 100644 --- a/freqtrade/commands/strategy_utils_commands.py +++ b/freqtrade/commands/strategy_utils_commands.py @@ -25,7 +25,7 @@ def start_strategy_update(args: Dict[str, Any]) -> None: config, enum_failed=False, recursive=config.get('recursive_strategy_search', False)) filtered_strategy_objs = [] - if hasattr(args, "strategy_list"): + if 'strategy_list' in args: for args_strategy in args['strategy_list']: for strategy_obj in strategy_objs: if (strategy_obj['name'] == args_strategy diff --git a/requirements.txt b/requirements.txt index 40bae63b6..14c468da0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -58,4 +58,4 @@ schedule==1.1.0 websockets==10.4 janus==1.0.0 -astor~=0.8.1 +ast-comments>=1.0.0 From d0045673faafeb4d6aa4c83f18cb65e192007153 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 3 Mar 2023 19:56:16 +0100 Subject: [PATCH 073/229] Add explicit test for stoploss_from_open --- tests/strategy/test_strategy_helpers.py | 30 +++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/tests/strategy/test_strategy_helpers.py b/tests/strategy/test_strategy_helpers.py index 36e997f7b..cb79ac171 100644 --- a/tests/strategy/test_strategy_helpers.py +++ b/tests/strategy/test_strategy_helpers.py @@ -169,6 +169,36 @@ def test_stoploss_from_open(side, profitrange): assert pytest.approx(stop_price) == expected_stop_price +@pytest.mark.parametrize("side,rel_stop,curr_profit,leverage,expected", [ + # profit range for long is [-1, inf] while for shorts is [-inf, 1] + ("long", 0, -1, 1, 1), + ("long", 0, 0.1, 1, 0.09090909), + ("long", -0.1, 0.1, 1, 0.18181818), + ("long", 0.1, 0.2, 1, 0.08333333), + ("long", 0.1, 0.5, 1, 0.266666666), + ("long", 0.1, 5, 1, 0.816666666), # 500% profit, set stoploss to 10% above open price + + ("short", 0, 0.1, 1, 0.1111111), + ("short", -0.1, 0.1, 1, 0.2222222), + ("short", 0.1, 0.2, 1, 0.125), + ("short", 0.1, 1, 1, 1), +]) +def test_stoploss_from_open_leverage(side, rel_stop, curr_profit, leverage, expected): + + stoploss = stoploss_from_open(rel_stop, curr_profit, side == 'short') + assert pytest.approx(stoploss) == expected + open_rate = 100 + if stoploss != 1: + if side == 'long': + current_rate = open_rate * (1 + curr_profit) + stop = current_rate * (1 - stoploss) + assert pytest.approx(stop) == open_rate * (1 + rel_stop) + else: + current_rate = open_rate * (1 - curr_profit) + stop = current_rate * (1 + stoploss) + assert pytest.approx(stop) == open_rate * (1 - rel_stop) + + def test_stoploss_from_absolute(): assert pytest.approx(stoploss_from_absolute(90, 100)) == 1 - (90 / 100) assert pytest.approx(stoploss_from_absolute(90, 100)) == 0.1 From 51c15d894b4ce98583875c37c149a0e3ad137909 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 4 Mar 2023 15:27:01 +0100 Subject: [PATCH 074/229] Bump ccxt to 2.8.88 closes #8270 --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 6b1c888b8..efd49a7f3 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,7 +2,7 @@ numpy==1.24.2 pandas==1.5.3 pandas-ta==0.3.14b -ccxt==2.8.54 +ccxt==2.8.88 cryptography==39.0.1 aiohttp==3.8.4 SQLAlchemy==2.0.4 From 027e0234430a6e9fb794c13b2a73aa73f529decd Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 4 Mar 2023 18:00:06 +0100 Subject: [PATCH 075/229] Stop from open with leverage --- freqtrade/strategy/strategy_helper.py | 13 ++++++++----- tests/strategy/test_strategy_helpers.py | 18 +++++++++++------- 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/freqtrade/strategy/strategy_helper.py b/freqtrade/strategy/strategy_helper.py index aa753a829..3ba1850b3 100644 --- a/freqtrade/strategy/strategy_helper.py +++ b/freqtrade/strategy/strategy_helper.py @@ -86,7 +86,8 @@ def merge_informative_pair(dataframe: pd.DataFrame, informative: pd.DataFrame, def stoploss_from_open( open_relative_stop: float, current_profit: float, - is_short: bool = False + is_short: bool = False, + leverage: float = 1.0 ) -> float: """ @@ -102,21 +103,23 @@ def stoploss_from_open( :param open_relative_stop: Desired stop loss percentage relative to open price :param current_profit: The current profit percentage :param is_short: When true, perform the calculation for short instead of long + :param leverage: Leverage to use for the calculation :return: Stop loss value relative to current price """ # formula is undefined for current_profit -1 (longs) or 1 (shorts), return maximum value - if (current_profit == -1 and not is_short) or (is_short and current_profit == 1): + _current_profit = current_profit / leverage + if (_current_profit == -1 and not is_short) or (is_short and _current_profit == 1): return 1 if is_short is True: - stoploss = -1 + ((1 - open_relative_stop) / (1 - current_profit)) + stoploss = -1 + ((1 - open_relative_stop / leverage) / (1 - _current_profit)) else: - stoploss = 1 - ((1 + open_relative_stop) / (1 + current_profit)) + stoploss = 1 - ((1 + open_relative_stop / leverage) / (1 + _current_profit)) # negative stoploss values indicate the requested stop price is higher/lower # (long/short) than the current price - return max(stoploss, 0.0) + return max(stoploss * leverage, 0.0) def stoploss_from_absolute(stop_rate: float, current_rate: float, is_short: bool = False) -> float: diff --git a/tests/strategy/test_strategy_helpers.py b/tests/strategy/test_strategy_helpers.py index cb79ac171..a55580780 100644 --- a/tests/strategy/test_strategy_helpers.py +++ b/tests/strategy/test_strategy_helpers.py @@ -177,26 +177,30 @@ def test_stoploss_from_open(side, profitrange): ("long", 0.1, 0.2, 1, 0.08333333), ("long", 0.1, 0.5, 1, 0.266666666), ("long", 0.1, 5, 1, 0.816666666), # 500% profit, set stoploss to 10% above open price + ("long", 0, 5, 10, 3.3333333), # 500% profit, set stoploss break even + ("long", 0.1, 5, 10, 3.26666666), # 500% profit, set stoploss to 10% above open price + ("long", -0.1, 5, 10, 3.3999999), # 500% profit, set stoploss to 10% belowopen price ("short", 0, 0.1, 1, 0.1111111), ("short", -0.1, 0.1, 1, 0.2222222), ("short", 0.1, 0.2, 1, 0.125), ("short", 0.1, 1, 1, 1), + ("short", -0.01, 5, 10, 10.01999999), # 500% profit at 10x ]) def test_stoploss_from_open_leverage(side, rel_stop, curr_profit, leverage, expected): - stoploss = stoploss_from_open(rel_stop, curr_profit, side == 'short') + stoploss = stoploss_from_open(rel_stop, curr_profit, side == 'short', leverage) assert pytest.approx(stoploss) == expected open_rate = 100 if stoploss != 1: if side == 'long': - current_rate = open_rate * (1 + curr_profit) - stop = current_rate * (1 - stoploss) - assert pytest.approx(stop) == open_rate * (1 + rel_stop) + current_rate = open_rate * (1 + curr_profit / leverage) + stop = current_rate * (1 - stoploss / leverage) + assert pytest.approx(stop) == open_rate * (1 + rel_stop / leverage) else: - current_rate = open_rate * (1 - curr_profit) - stop = current_rate * (1 + stoploss) - assert pytest.approx(stop) == open_rate * (1 - rel_stop) + current_rate = open_rate * (1 - curr_profit / leverage) + stop = current_rate * (1 + stoploss / leverage) + assert pytest.approx(stop) == open_rate * (1 - rel_stop / leverage) def test_stoploss_from_absolute(): From f0cbb4f94973435a99037a4d7f3ba45a005ddd0c Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 4 Mar 2023 18:20:31 +0100 Subject: [PATCH 076/229] Expose relative realized profit --- freqtrade/persistence/trade_model.py | 2 ++ freqtrade/rpc/api_server/api_schemas.py | 1 + tests/persistence/test_persistence.py | 2 ++ tests/rpc/test_rpc.py | 1 + 4 files changed, 6 insertions(+) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 1c37635f0..21fe80819 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -519,6 +519,8 @@ class LocalTrade(): 'close_timestamp': int(self.close_date.replace( tzinfo=timezone.utc).timestamp() * 1000) if self.close_date else None, 'realized_profit': self.realized_profit or 0.0, + # Close-profit corresponds to relative realized_profit ratio + 'realized_profit_ratio': self.close_profit or None, 'close_rate': self.close_rate, 'close_rate_requested': self.close_rate_requested, 'close_profit': self.close_profit, # Deprecated diff --git a/freqtrade/rpc/api_server/api_schemas.py b/freqtrade/rpc/api_server/api_schemas.py index 562c9aa7d..a751179b2 100644 --- a/freqtrade/rpc/api_server/api_schemas.py +++ b/freqtrade/rpc/api_server/api_schemas.py @@ -250,6 +250,7 @@ class TradeSchema(BaseModel): profit_fiat: Optional[float] realized_profit: float + realized_profit_ratio: Optional[float] exit_reason: Optional[str] exit_order_status: Optional[str] diff --git a/tests/persistence/test_persistence.py b/tests/persistence/test_persistence.py index 6d907ccf0..0598d4134 100644 --- a/tests/persistence/test_persistence.py +++ b/tests/persistence/test_persistence.py @@ -1362,6 +1362,7 @@ def test_to_json(fee): 'trade_duration': None, 'trade_duration_s': None, 'realized_profit': 0.0, + 'realized_profit_ratio': None, 'close_profit': None, 'close_profit_pct': None, 'close_profit_abs': None, @@ -1438,6 +1439,7 @@ def test_to_json(fee): 'initial_stop_loss_pct': None, 'initial_stop_loss_ratio': None, 'realized_profit': 0.0, + 'realized_profit_ratio': None, 'close_profit': None, 'close_profit_pct': None, 'close_profit_abs': None, diff --git a/tests/rpc/test_rpc.py b/tests/rpc/test_rpc.py index d368107df..cd72da763 100644 --- a/tests/rpc/test_rpc.py +++ b/tests/rpc/test_rpc.py @@ -76,6 +76,7 @@ def test_rpc_trade_status(default_conf, ticker, fee, mocker) -> None: 'stoploss_entry_dist_ratio': -0.10376381, 'open_order': None, 'realized_profit': 0.0, + 'realized_profit_ratio': None, 'total_profit_abs': -4.09e-06, 'total_profit_fiat': ANY, 'exchange': 'binance', From aec11618cefb3af94d19105610442d111edd4ddf Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 4 Mar 2023 18:26:16 +0100 Subject: [PATCH 077/229] Telegram improved formatting --- freqtrade/rpc/telegram.py | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/freqtrade/rpc/telegram.py b/freqtrade/rpc/telegram.py index 6f82a7316..175d0ce93 100644 --- a/freqtrade/rpc/telegram.py +++ b/freqtrade/rpc/telegram.py @@ -321,28 +321,30 @@ class Telegram(RPCHandler): and self._rpc._fiat_converter): msg['profit_fiat'] = self._rpc._fiat_converter.convert_amount( msg['profit_amount'], msg['stake_currency'], msg['fiat_currency']) - msg['profit_extra'] = ( - f" / {msg['profit_fiat']:.3f} {msg['fiat_currency']}") + msg['profit_extra'] = f" / {msg['profit_fiat']:.3f} {msg['fiat_currency']}" else: msg['profit_extra'] = '' msg['profit_extra'] = ( f" ({msg['gain']}: {msg['profit_amount']:.8f} {msg['stake_currency']}" f"{msg['profit_extra']})") + is_fill = msg['type'] == RPCMessageType.EXIT_FILL is_sub_trade = msg.get('sub_trade') is_sub_profit = msg['profit_amount'] != msg.get('cumulative_profit') - profit_prefix = ('Sub ' if is_sub_profit - else 'Cumulative ') if is_sub_trade else '' + profit_prefix = ('Sub ' if is_sub_profit else 'Cumulative ') if is_sub_trade else '' cp_extra = '' + if is_sub_profit and is_sub_trade: if self._rpc._fiat_converter: cp_fiat = self._rpc._fiat_converter.convert_amount( msg['cumulative_profit'], msg['stake_currency'], msg['fiat_currency']) cp_extra = f" / {cp_fiat:.3f} {msg['fiat_currency']}" - else: - cp_extra = '' - cp_extra = f"*Cumulative Profit:* (`{msg['cumulative_profit']:.8f} " \ - f"{msg['stake_currency']}{cp_extra}`)\n" + + cp_extra = ( + f"*Cumulative Profit:* (`{msg['cumulative_profit']:.8f} " + f"{msg['stake_currency']}{cp_extra}`)\n" + ) + message = ( f"{msg['emoji']} *{self._exchange_from_msg(msg)}:* " f"{'Exited' if is_fill else 'Exiting'} {msg['pair']} (#{msg['trade_id']})\n" @@ -364,7 +366,7 @@ class Telegram(RPCHandler): elif msg['type'] == RPCMessageType.EXIT_FILL: message += f"*Exit Rate:* `{msg['close_rate']:.8f}`" - if msg.get('sub_trade'): + if is_sub_trade: if self._rpc._fiat_converter: msg['stake_amount_fiat'] = self._rpc._fiat_converter.convert_amount( msg['stake_amount'], msg['stake_currency'], msg['fiat_currency']) @@ -597,7 +599,8 @@ class Telegram(RPCHandler): if r['is_open']: if r.get('realized_profit'): - lines.append("*Realized Profit:* `{realized_profit_r}`") + lines.append( + "*Realized Profit:* `{realized_profit_r} {realized_profit_ratio:.2%}`") lines.append("*Total Profit:* `{total_profit_abs_r}` ") if (r['stop_loss_abs'] != r['initial_stop_loss_abs'] From 548db188571f999c3315302fb5f3dff67765ac9b Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 4 Mar 2023 19:27:55 +0100 Subject: [PATCH 078/229] Improve wording on partial exit notifications --- freqtrade/rpc/telegram.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/freqtrade/rpc/telegram.py b/freqtrade/rpc/telegram.py index 175d0ce93..874ae884a 100644 --- a/freqtrade/rpc/telegram.py +++ b/freqtrade/rpc/telegram.py @@ -333,13 +333,13 @@ class Telegram(RPCHandler): is_sub_profit = msg['profit_amount'] != msg.get('cumulative_profit') profit_prefix = ('Sub ' if is_sub_profit else 'Cumulative ') if is_sub_trade else '' cp_extra = '' - + exit_wording = 'Exited' if is_fill else 'Exiting' if is_sub_profit and is_sub_trade: if self._rpc._fiat_converter: cp_fiat = self._rpc._fiat_converter.convert_amount( msg['cumulative_profit'], msg['stake_currency'], msg['fiat_currency']) cp_extra = f" / {cp_fiat:.3f} {msg['fiat_currency']}" - + exit_wording = f"Partially {exit_wording.lower()}" cp_extra = ( f"*Cumulative Profit:* (`{msg['cumulative_profit']:.8f} " f"{msg['stake_currency']}{cp_extra}`)\n" @@ -347,7 +347,7 @@ class Telegram(RPCHandler): message = ( f"{msg['emoji']} *{self._exchange_from_msg(msg)}:* " - f"{'Exited' if is_fill else 'Exiting'} {msg['pair']} (#{msg['trade_id']})\n" + f"{exit_wording} {msg['pair']} (#{msg['trade_id']})\n" f"{self._add_analyzed_candle(msg['pair'])}" f"*{f'{profit_prefix}Profit' if is_fill else f'Unrealized {profit_prefix}Profit'}:* " f"`{msg['profit_ratio']:.2%}{msg['profit_extra']}`\n" From 60e651b48103571074c9181112279cd7880735b7 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 4 Mar 2023 19:49:37 +0100 Subject: [PATCH 079/229] Updat bybit ohlcv data to v5 --- freqtrade/exchange/bybit.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/freqtrade/exchange/bybit.py b/freqtrade/exchange/bybit.py index c565b891f..6f841b608 100644 --- a/freqtrade/exchange/bybit.py +++ b/freqtrade/exchange/bybit.py @@ -27,11 +27,10 @@ class Bybit(Exchange): """ _ft_has: Dict = { - "ohlcv_candle_limit": 1000, + "ohlcv_candle_limit": 200, "ohlcv_has_history": False, } _ft_has_futures: Dict = { - "ohlcv_candle_limit": 200, "ohlcv_has_history": True, "mark_ohlcv_timeframe": "4h", "funding_fee_timeframe": "8h", From 3f6795962f421710e3a5e5b359c4e6b2ad6a8551 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 4 Mar 2023 19:49:59 +0100 Subject: [PATCH 080/229] Update bybit orderbook test --- tests/exchange/test_ccxt_compat.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/exchange/test_ccxt_compat.py b/tests/exchange/test_ccxt_compat.py index f06a53308..872cf5059 100644 --- a/tests/exchange/test_ccxt_compat.py +++ b/tests/exchange/test_ccxt_compat.py @@ -463,7 +463,9 @@ class TestCCXTExchange(): if exchangename == 'gate': # TODO: Gate is unstable here at the moment, ignoring the limit partially. return - for val in [1, 2, 5, 25, 100]: + for val in [1, 2, 5, 25, 50, 100]: + if val > 50 and exchangename == 'bybit': + continue l2 = exch.fetch_l2_order_book(pair, val) if not l2_limit_range or val in l2_limit_range: if val > 50: From c1d395a7d88f6f33daca91a6885c0de17f3333a2 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 4 Mar 2023 20:02:20 +0100 Subject: [PATCH 081/229] Revert "Bump ccxt to 2.8.88" This reverts commit 51c15d894b4ce98583875c37c149a0e3ad137909. --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index efd49a7f3..6b1c888b8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,7 +2,7 @@ numpy==1.24.2 pandas==1.5.3 pandas-ta==0.3.14b -ccxt==2.8.88 +ccxt==2.8.54 cryptography==39.0.1 aiohttp==3.8.4 SQLAlchemy==2.0.4 From 7c0c98a36881b339243c5f49a86231a63c4788d8 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 4 Mar 2023 20:08:20 +0100 Subject: [PATCH 082/229] Properly format first entry value, too. --- freqtrade/rpc/telegram.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/freqtrade/rpc/telegram.py b/freqtrade/rpc/telegram.py index 874ae884a..fdfad902c 100644 --- a/freqtrade/rpc/telegram.py +++ b/freqtrade/rpc/telegram.py @@ -488,7 +488,9 @@ class Telegram(RPCHandler): if order_nr == 1: lines.append(f"*{wording} #{order_nr}:*") lines.append( - f"*Amount:* {cur_entry_amount} ({order['cost']:.8f} {quote_currency})") + f"*Amount:* {cur_entry_amount} " + f"({round_coin_value(order['cost'], quote_currency)})" + ) lines.append(f"*Average Price:* {cur_entry_average}") else: sum_stake = 0 From 9444bbb6f3e98611c01968e3f6f01fa3c8b4285f Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 4 Mar 2023 20:09:39 +0100 Subject: [PATCH 083/229] `/maxentries` should be in single tics. --- freqtrade/rpc/telegram.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/freqtrade/rpc/telegram.py b/freqtrade/rpc/telegram.py index fdfad902c..1a96b1671 100644 --- a/freqtrade/rpc/telegram.py +++ b/freqtrade/rpc/telegram.py @@ -586,7 +586,7 @@ class Telegram(RPCHandler): if position_adjust: max_buy_str = (f"/{max_entries + 1}" if (max_entries > 0) else "") - lines.append("*Number of Entries:* `{num_entries}`" + max_buy_str) + lines.append("*Number of Entries:* `{num_entries}" + max_buy_str + "`") lines.append("*Number of Exits:* `{num_exits}`") lines.extend([ From 108a578772564b440a856a2268560de32fe2d5ec Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 4 Mar 2023 20:17:19 +0100 Subject: [PATCH 084/229] Update tests to latest rpc changes --- tests/rpc/test_rpc_apiserver.py | 2 ++ tests/rpc/test_rpc_telegram.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index f898dd476..e140a43f1 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -1013,6 +1013,7 @@ def test_api_status(botclient, mocker, ticker, fee, markets, is_short, 'total_profit_abs': ANY, 'total_profit_fiat': ANY, 'realized_profit': 0.0, + 'realized_profit_ratio': None, 'current_rate': current_rate, 'open_date': ANY, 'open_timestamp': ANY, @@ -1243,6 +1244,7 @@ def test_api_force_entry(botclient, mocker, fee, endpoint): 'profit_abs': None, 'profit_fiat': None, 'realized_profit': 0.0, + 'realized_profit_ratio': None, 'fee_close': 0.0025, 'fee_close_cost': None, 'fee_close_currency': None, diff --git a/tests/rpc/test_rpc_telegram.py b/tests/rpc/test_rpc_telegram.py index 26cb93821..69d0f805d 100644 --- a/tests/rpc/test_rpc_telegram.py +++ b/tests/rpc/test_rpc_telegram.py @@ -2012,7 +2012,7 @@ def test_send_msg_sell_notification(default_conf, mocker) -> None: 'sub_trade': True, }) assert msg_mock.call_args[0][0] == ( - '\N{WARNING SIGN} *Binance (dry):* Exiting KEY/ETH (#1)\n' + '\N{WARNING SIGN} *Binance (dry):* Partially exiting KEY/ETH (#1)\n' '*Unrealized Sub Profit:* `-57.41% (loss: -0.05746268 ETH / -24.812 USD)`\n' '*Cumulative Profit:* (`-0.15746268 ETH / -24.812 USD`)\n' '*Enter Tag:* `buy_signal1`\n' From d80760d20c9b663f64bcd530ed2e4c84d7a7ab2e Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 5 Mar 2023 14:16:53 +0100 Subject: [PATCH 085/229] bump ccxt to 2.8.98 --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 6b1c888b8..a6b3ddd51 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,7 +2,7 @@ numpy==1.24.2 pandas==1.5.3 pandas-ta==0.3.14b -ccxt==2.8.54 +ccxt==2.8.98 cryptography==39.0.1 aiohttp==3.8.4 SQLAlchemy==2.0.4 From d0d6f53dec489d022fd301375bf4478646b0a41f Mon Sep 17 00:00:00 2001 From: hippocritical Date: Sun, 5 Mar 2023 16:19:26 +0100 Subject: [PATCH 086/229] fixed github formatting errors --- freqtrade/commands/strategy_utils_commands.py | 6 +++--- freqtrade/strategy/strategyupdater.py | 7 +++---- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/freqtrade/commands/strategy_utils_commands.py b/freqtrade/commands/strategy_utils_commands.py index 0124b73b6..aca368742 100644 --- a/freqtrade/commands/strategy_utils_commands.py +++ b/freqtrade/commands/strategy_utils_commands.py @@ -1,6 +1,6 @@ import logging -import os import time +from pathlib import Path from typing import Any, Dict from freqtrade.configuration import setup_utils_configuration @@ -45,11 +45,11 @@ def start_strategy_update(args: Dict[str, Any]) -> None: def start_conversion(strategy_obj, config): # try: - print(f"Conversion of {os.path.basename(strategy_obj['location'])} started.") + print(f"Conversion of {Path(strategy_obj['location']).name} started.") instance_strategy_updater = StrategyUpdater() start = time.perf_counter() instance_strategy_updater.start(config, strategy_obj) elapsed = time.perf_counter() - start - print(f"Conversion of {os.path.basename(strategy_obj['location'])} took {elapsed:.1f} seconds.") + print(f"Conversion of {Path(strategy_obj['location']).name} took {elapsed:.1f} seconds.") # except: # pass diff --git a/freqtrade/strategy/strategyupdater.py b/freqtrade/strategy/strategyupdater.py index db19d4fba..6fe1f326c 100644 --- a/freqtrade/strategy/strategyupdater.py +++ b/freqtrade/strategy/strategyupdater.py @@ -1,4 +1,3 @@ -import os import shutil from pathlib import Path @@ -55,10 +54,10 @@ class StrategyUpdater: target_file = Path.joinpath(strategies_backup_folder, strategy_obj['location_rel']) # read the file - with open(source_file, 'r') as f: + with Path(source_file).open('r') as f: old_code = f.read() if not strategies_backup_folder.is_dir(): - os.makedirs(strategies_backup_folder) + Path(strategies_backup_folder).mkdir(parents=True, exist_ok=True) # backup original # => currently no date after the filename, @@ -69,7 +68,7 @@ class StrategyUpdater: # update the code new_code = self.update_code(old_code) # write the modified code to the destination folder - with open(source_file, 'w') as f: + with Path(source_file).open('w') as f: f.write(new_code) # define the function to update the code From b072fae507200321d2a4cb3ce81f27e2eb879d34 Mon Sep 17 00:00:00 2001 From: hippocritical Date: Sun, 5 Mar 2023 18:48:32 +0100 Subject: [PATCH 087/229] added strategy-updater compartment inside utils.md --- docs/utils.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/docs/utils.md b/docs/utils.md index 87c7f6aa6..3d6eda3ce 100644 --- a/docs/utils.md +++ b/docs/utils.md @@ -947,7 +947,6 @@ Common arguments: --userdir PATH, --user-data-dir PATH Path to userdata directory. ``` - ### Examples Print trades with id 2 and 3 as json @@ -955,3 +954,13 @@ Print trades with id 2 and 3 as json ``` bash freqtrade show-trades --db-url sqlite:///tradesv3.sqlite --trade-ids 2 3 --print-json ``` + +### Strategy-Updater +Updates a list strategies or all strategies within the strategies folder to be v3 compliant including futures. +If the command runs without --strategy-list then all files inside the strategies folder will be converted. +``` +usage: freqtrade strategy_updater + +optional arguments: + --strategy-list defines a list of strategies that should be converted +``` From 0bdd238d7ff2ebf748b705f0cb239767925eeade Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 6 Mar 2023 03:56:37 +0000 Subject: [PATCH 088/229] Bump orjson from 3.8.6 to 3.8.7 Bumps [orjson](https://github.com/ijl/orjson) from 3.8.6 to 3.8.7. - [Release notes](https://github.com/ijl/orjson/releases) - [Changelog](https://github.com/ijl/orjson/blob/master/CHANGELOG.md) - [Commits](https://github.com/ijl/orjson/compare/3.8.6...3.8.7) --- updated-dependencies: - dependency-name: orjson dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index a6b3ddd51..8f5c2f46d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -28,7 +28,7 @@ py_find_1st==1.1.5 # Load ticker files 30% faster python-rapidjson==1.9 # Properly format api responses -orjson==3.8.6 +orjson==3.8.7 # Notify systemd sdnotify==0.3.2 From f4c17be8dec5dd176a73fa5fb07d752e79443087 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 6 Mar 2023 03:56:44 +0000 Subject: [PATCH 089/229] Bump ruff from 0.0.253 to 0.0.254 Bumps [ruff](https://github.com/charliermarsh/ruff) from 0.0.253 to 0.0.254. - [Release notes](https://github.com/charliermarsh/ruff/releases) - [Changelog](https://github.com/charliermarsh/ruff/blob/main/BREAKING_CHANGES.md) - [Commits](https://github.com/charliermarsh/ruff/compare/v0.0.253...v0.0.254) --- updated-dependencies: - dependency-name: ruff dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 2ba004f8d..4c009fc42 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -7,7 +7,7 @@ -r docs/requirements-docs.txt coveralls==3.3.1 -ruff==0.0.253 +ruff==0.0.254 mypy==1.0.1 pre-commit==3.1.1 pytest==7.2.1 From 8484427cf879a4dae7aee02a504811d6c7e99b75 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 6 Mar 2023 03:56:54 +0000 Subject: [PATCH 090/229] Bump cryptography from 39.0.1 to 39.0.2 Bumps [cryptography](https://github.com/pyca/cryptography) from 39.0.1 to 39.0.2. - [Release notes](https://github.com/pyca/cryptography/releases) - [Changelog](https://github.com/pyca/cryptography/blob/main/CHANGELOG.rst) - [Commits](https://github.com/pyca/cryptography/compare/39.0.1...39.0.2) --- updated-dependencies: - dependency-name: cryptography dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index a6b3ddd51..1f22bc033 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,7 +3,7 @@ pandas==1.5.3 pandas-ta==0.3.14b ccxt==2.8.98 -cryptography==39.0.1 +cryptography==39.0.2 aiohttp==3.8.4 SQLAlchemy==2.0.4 python-telegram-bot==13.15 From 57969f8b0164579df9f5bd1b80504598a2b84e70 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 6 Mar 2023 03:56:58 +0000 Subject: [PATCH 091/229] Bump prompt-toolkit from 3.0.37 to 3.0.38 Bumps [prompt-toolkit](https://github.com/prompt-toolkit/python-prompt-toolkit) from 3.0.37 to 3.0.38. - [Release notes](https://github.com/prompt-toolkit/python-prompt-toolkit/releases) - [Changelog](https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/CHANGELOG) - [Commits](https://github.com/prompt-toolkit/python-prompt-toolkit/compare/3.0.37...3.0.38) --- updated-dependencies: - dependency-name: prompt-toolkit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index a6b3ddd51..efd858f45 100644 --- a/requirements.txt +++ b/requirements.txt @@ -45,7 +45,7 @@ psutil==5.9.4 colorama==0.4.6 # Building config files interactively questionary==1.10.0 -prompt-toolkit==3.0.37 +prompt-toolkit==3.0.38 # Extensions to datetime library python-dateutil==2.8.2 From d1d9e25c2e8707edbbc905f53e7722bfe5b5af4b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 6 Mar 2023 03:57:03 +0000 Subject: [PATCH 092/229] Bump mkdocs-material from 9.0.15 to 9.1.1 Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 9.0.15 to 9.1.1. - [Release notes](https://github.com/squidfunk/mkdocs-material/releases) - [Changelog](https://github.com/squidfunk/mkdocs-material/blob/master/CHANGELOG) - [Commits](https://github.com/squidfunk/mkdocs-material/compare/9.0.15...9.1.1) --- updated-dependencies: - dependency-name: mkdocs-material dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- docs/requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/requirements-docs.txt b/docs/requirements-docs.txt index 065411018..2ca11dabf 100644 --- a/docs/requirements-docs.txt +++ b/docs/requirements-docs.txt @@ -1,6 +1,6 @@ markdown==3.3.7 mkdocs==1.4.2 -mkdocs-material==9.0.15 +mkdocs-material==9.1.1 mdx_truly_sane_lists==1.3 pymdown-extensions==9.9.2 jinja2==3.1.2 From 48e16f6aba7a4d2ed33958a473144e62e3cac32d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 6 Mar 2023 03:57:18 +0000 Subject: [PATCH 093/229] Bump sqlalchemy from 2.0.4 to 2.0.5.post1 Bumps [sqlalchemy](https://github.com/sqlalchemy/sqlalchemy) from 2.0.4 to 2.0.5.post1. - [Release notes](https://github.com/sqlalchemy/sqlalchemy/releases) - [Changelog](https://github.com/sqlalchemy/sqlalchemy/blob/main/CHANGES.rst) - [Commits](https://github.com/sqlalchemy/sqlalchemy/commits) --- updated-dependencies: - dependency-name: sqlalchemy dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index a6b3ddd51..6eeecfde6 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,7 +5,7 @@ pandas-ta==0.3.14b ccxt==2.8.98 cryptography==39.0.1 aiohttp==3.8.4 -SQLAlchemy==2.0.4 +SQLAlchemy==2.0.5.post1 python-telegram-bot==13.15 arrow==1.2.3 cachetools==4.2.2 From a57b033745558bc6e61de9704dfab3e2e5f20e1a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 6 Mar 2023 03:57:27 +0000 Subject: [PATCH 094/229] Bump types-python-dateutil from 2.8.19.9 to 2.8.19.10 Bumps [types-python-dateutil](https://github.com/python/typeshed) from 2.8.19.9 to 2.8.19.10. - [Release notes](https://github.com/python/typeshed/releases) - [Commits](https://github.com/python/typeshed/commits) --- updated-dependencies: - dependency-name: types-python-dateutil dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 2ba004f8d..a945ffc63 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -29,4 +29,4 @@ types-cachetools==5.3.0.4 types-filelock==3.2.7 types-requests==2.28.11.15 types-tabulate==0.9.0.1 -types-python-dateutil==2.8.19.9 +types-python-dateutil==2.8.19.10 From 9750e9ca4ef54d11f4525b79ea3ff9664b4a43e5 Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 6 Mar 2023 06:32:33 +0100 Subject: [PATCH 095/229] pre-commit python-dateutil --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 565eb96f7..402e5641d 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -17,7 +17,7 @@ repos: - types-filelock==3.2.7 - types-requests==2.28.11.15 - types-tabulate==0.9.0.1 - - types-python-dateutil==2.8.19.9 + - types-python-dateutil==2.8.19.10 - SQLAlchemy==2.0.4 # stages: [push] From 25fd4a04d6460ed2a00af144d7fcb291669a1943 Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 6 Mar 2023 06:34:37 +0100 Subject: [PATCH 096/229] Update sqlalchemy QueryPropertyDescriptor to match latest version --- .pre-commit-config.yaml | 2 +- freqtrade/persistence/pairlock.py | 5 ++--- freqtrade/persistence/trade_model.py | 8 ++++---- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 565eb96f7..895916c15 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -18,7 +18,7 @@ repos: - types-requests==2.28.11.15 - types-tabulate==0.9.0.1 - types-python-dateutil==2.8.19.9 - - SQLAlchemy==2.0.4 + - SQLAlchemy==2.0.5.post1 # stages: [push] - repo: https://github.com/pycqa/isort diff --git a/freqtrade/persistence/pairlock.py b/freqtrade/persistence/pairlock.py index a6d1eeaf0..1e5699145 100644 --- a/freqtrade/persistence/pairlock.py +++ b/freqtrade/persistence/pairlock.py @@ -2,8 +2,7 @@ from datetime import datetime, timezone from typing import Any, ClassVar, Dict, Optional from sqlalchemy import String, or_ -from sqlalchemy.orm import Mapped, Query, mapped_column -from sqlalchemy.orm.scoping import _QueryDescriptorType +from sqlalchemy.orm import Mapped, Query, QueryPropertyDescriptor, mapped_column from freqtrade.constants import DATETIME_PRINT_FORMAT from freqtrade.persistence.base import ModelBase, SessionType @@ -14,7 +13,7 @@ class PairLock(ModelBase): Pair Locks database model. """ __tablename__ = 'pairlocks' - query: ClassVar[_QueryDescriptorType] + query: ClassVar[QueryPropertyDescriptor] _session: ClassVar[SessionType] id: Mapped[int] = mapped_column(primary_key=True) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 21fe80819..8e8a414c8 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -8,8 +8,8 @@ from math import isclose from typing import Any, ClassVar, Dict, List, Optional, cast from sqlalchemy import Enum, Float, ForeignKey, Integer, String, UniqueConstraint, desc, func -from sqlalchemy.orm import Mapped, Query, lazyload, mapped_column, relationship -from sqlalchemy.orm.scoping import _QueryDescriptorType +from sqlalchemy.orm import (Mapped, Query, QueryPropertyDescriptor, lazyload, mapped_column, + relationship) from freqtrade.constants import (DATETIME_PRINT_FORMAT, MATH_CLOSE_PREC, NON_OPEN_EXCHANGE_STATES, BuySell, LongShort) @@ -36,7 +36,7 @@ class Order(ModelBase): Mirrors CCXT Order structure """ __tablename__ = 'orders' - query: ClassVar[_QueryDescriptorType] + query: ClassVar[QueryPropertyDescriptor] _session: ClassVar[SessionType] # Uniqueness should be ensured over pair, order_id @@ -1181,7 +1181,7 @@ class Trade(ModelBase, LocalTrade): Note: Fields must be aligned with LocalTrade class """ __tablename__ = 'trades' - query: ClassVar[_QueryDescriptorType] + query: ClassVar[QueryPropertyDescriptor] _session: ClassVar[SessionType] use_db: bool = True From 0fe72510d5cbaa8389070cf75e1e4cedf880008d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 6 Mar 2023 05:36:16 +0000 Subject: [PATCH 097/229] Bump pymdown-extensions from 9.9.2 to 9.10 Bumps [pymdown-extensions](https://github.com/facelessuser/pymdown-extensions) from 9.9.2 to 9.10. - [Release notes](https://github.com/facelessuser/pymdown-extensions/releases) - [Commits](https://github.com/facelessuser/pymdown-extensions/compare/9.9.2...9.10) --- updated-dependencies: - dependency-name: pymdown-extensions dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- docs/requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/requirements-docs.txt b/docs/requirements-docs.txt index 2ca11dabf..1b9a1f9b7 100644 --- a/docs/requirements-docs.txt +++ b/docs/requirements-docs.txt @@ -2,5 +2,5 @@ markdown==3.3.7 mkdocs==1.4.2 mkdocs-material==9.1.1 mdx_truly_sane_lists==1.3 -pymdown-extensions==9.9.2 +pymdown-extensions==9.10 jinja2==3.1.2 From de015a2d7e23e4d006e1cd84c7e12e1cd2378dad Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 5 Mar 2023 18:04:30 +0100 Subject: [PATCH 098/229] Improve telegram message formatting --- freqtrade/rpc/telegram.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/freqtrade/rpc/telegram.py b/freqtrade/rpc/telegram.py index 1a96b1671..e8a8a941f 100644 --- a/freqtrade/rpc/telegram.py +++ b/freqtrade/rpc/telegram.py @@ -510,14 +510,14 @@ class Telegram(RPCHandler): if prev_avg_price: minus_on_entry = (cur_entry_average - prev_avg_price) / prev_avg_price - lines.append(f"*{wording} #{order_nr}:* at {minus_on_entry:.2%} avg profit") + lines.append(f"*{wording} #{order_nr}:* at {minus_on_entry:.2%} avg Profit") if is_open: lines.append("({})".format(cur_entry_datetime .humanize(granularity=["day", "hour", "minute"]))) lines.append(f"*Amount:* {cur_entry_amount} " f"({round_coin_value(order['cost'], quote_currency)})") lines.append(f"*Average {wording} Price:* {cur_entry_average} " - f"({price_to_1st_entry:.2%} from 1st entry rate)") + f"({price_to_1st_entry:.2%} from 1st entry Rate)") lines.append(f"*Order filled:* {order['order_filled_date']}") # TODO: is this really useful? From 11eea9b4e1cef0a9bfceb27b37cfe8b7a10cc89f Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 5 Mar 2023 18:05:42 +0100 Subject: [PATCH 099/229] Fix formatting for /status Realized profit --- freqtrade/rpc/telegram.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/freqtrade/rpc/telegram.py b/freqtrade/rpc/telegram.py index e8a8a941f..7452005db 100644 --- a/freqtrade/rpc/telegram.py +++ b/freqtrade/rpc/telegram.py @@ -602,7 +602,7 @@ class Telegram(RPCHandler): if r['is_open']: if r.get('realized_profit'): lines.append( - "*Realized Profit:* `{realized_profit_r} {realized_profit_ratio:.2%}`") + "*Realized Profit:* `{realized_profit_ratio:.2%} ({realized_profit_r})`") lines.append("*Total Profit:* `{total_profit_abs_r}` ") if (r['stop_loss_abs'] != r['initial_stop_loss_abs'] From ca789b3282926c3e40f2be1e905034be001c2abb Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 5 Mar 2023 18:11:10 +0100 Subject: [PATCH 100/229] /status - whitespace --- freqtrade/rpc/telegram.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/freqtrade/rpc/telegram.py b/freqtrade/rpc/telegram.py index 7452005db..2e87eabc9 100644 --- a/freqtrade/rpc/telegram.py +++ b/freqtrade/rpc/telegram.py @@ -594,7 +594,7 @@ class Telegram(RPCHandler): "*Close Rate:* `{close_rate:.8f}`" if r['close_rate'] else "", "*Open Date:* `{open_date}`", "*Close Date:* `{close_date}`" if r['close_date'] else "", - "*Current Rate:* `{current_rate:.8f}`" if r['is_open'] else "", + "\n*Current Rate:* `{current_rate:.8f}`" if r['is_open'] else "", ("*Unrealized Profit:* " if r['is_open'] else "*Close Profit: *") + "`{profit_ratio:.2%}` `({profit_abs_r})`", ]) @@ -605,6 +605,8 @@ class Telegram(RPCHandler): "*Realized Profit:* `{realized_profit_ratio:.2%} ({realized_profit_r})`") lines.append("*Total Profit:* `{total_profit_abs_r}` ") + # Append empty line to improve readability + lines.append(" ") if (r['stop_loss_abs'] != r['initial_stop_loss_abs'] and r['initial_stop_loss_ratio'] is not None): # Adding initial stoploss only if it is different from stoploss From fff08f737f29471ada06a336c4b0aefe0ec6c621 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 5 Mar 2023 19:17:39 +0100 Subject: [PATCH 101/229] /status msg - improve formatting further --- freqtrade/rpc/telegram.py | 11 ++++++++--- tests/rpc/test_rpc_telegram.py | 1 + 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/freqtrade/rpc/telegram.py b/freqtrade/rpc/telegram.py index 2e87eabc9..19027f4d5 100644 --- a/freqtrade/rpc/telegram.py +++ b/freqtrade/rpc/telegram.py @@ -569,6 +569,8 @@ class Telegram(RPCHandler): and not o['ft_order_side'] == 'stoploss']) r['exit_reason'] = r.get('exit_reason', "") r['stake_amount_r'] = round_coin_value(r['stake_amount'], r['quote_currency']) + r['max_stake_amount_r'] = round_coin_value( + r['max_stake_amount'] or r['stake_amount'], r['quote_currency']) r['profit_abs_r'] = round_coin_value(r['profit_abs'], r['quote_currency']) r['realized_profit_r'] = round_coin_value(r['realized_profit'], r['quote_currency']) r['total_profit_abs_r'] = round_coin_value( @@ -580,21 +582,24 @@ class Telegram(RPCHandler): f"*Direction:* {'`Short`' if r.get('is_short') else '`Long`'}" + " ` ({leverage}x)`" if r.get('leverage') else "", "*Amount:* `{amount} ({stake_amount_r})`", + "*Total invested:* `{max_stake_amount_r}`" if position_adjust else "", "*Enter Tag:* `{enter_tag}`" if r['enter_tag'] else "", "*Exit Reason:* `{exit_reason}`" if r['exit_reason'] else "", ] if position_adjust: max_buy_str = (f"/{max_entries + 1}" if (max_entries > 0) else "") - lines.append("*Number of Entries:* `{num_entries}" + max_buy_str + "`") - lines.append("*Number of Exits:* `{num_exits}`") + lines.extend([ + "*Number of Entries:* `{num_entries}" + max_buy_str + "`", + "*Number of Exits:* `{num_exits}`" + ]) lines.extend([ "*Open Rate:* `{open_rate:.8f}`", "*Close Rate:* `{close_rate:.8f}`" if r['close_rate'] else "", "*Open Date:* `{open_date}`", "*Close Date:* `{close_date}`" if r['close_date'] else "", - "\n*Current Rate:* `{current_rate:.8f}`" if r['is_open'] else "", + " \n*Current Rate:* `{current_rate:.8f}`" if r['is_open'] else "", ("*Unrealized Profit:* " if r['is_open'] else "*Close Profit: *") + "`{profit_ratio:.2%}` `({profit_abs_r})`", ]) diff --git a/tests/rpc/test_rpc_telegram.py b/tests/rpc/test_rpc_telegram.py index 69d0f805d..1dc255b3e 100644 --- a/tests/rpc/test_rpc_telegram.py +++ b/tests/rpc/test_rpc_telegram.py @@ -198,6 +198,7 @@ def test_telegram_status(default_conf, update, mocker) -> None: 'current_rate': 1.098e-05, 'amount': 90.99181074, 'stake_amount': 90.99181074, + 'max_stake_amount': 90.99181074, 'buy_tag': None, 'enter_tag': None, 'close_profit_ratio': None, From 9d285e3dc04e1b4c2c0ae1d01a17198f4f0cac86 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 5 Mar 2023 19:35:06 +0100 Subject: [PATCH 102/229] Add total_profit_ratio to telegram output part of #8234 --- freqtrade/rpc/rpc.py | 6 ++++++ freqtrade/rpc/telegram.py | 7 ++++--- tests/rpc/test_rpc.py | 2 ++ 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 8692c477f..4b3f6209e 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -192,6 +192,11 @@ class RPC: current_profit = trade.close_profit or 0.0 current_profit_abs = trade.close_profit_abs or 0.0 total_profit_abs = trade.realized_profit + current_profit_abs + total_profit_ratio = 0.0 + if trade.max_stake_amount: + total_profit_ratio = ( + (total_profit_abs / trade.max_stake_amount) * trade.leverage + ) # Calculate fiat profit if not isnan(current_profit_abs) and self._fiat_converter: @@ -224,6 +229,7 @@ class RPC: total_profit_abs=total_profit_abs, total_profit_fiat=total_profit_fiat, + total_profit_ratio=total_profit_ratio, stoploss_current_dist=stoploss_current_dist, stoploss_current_dist_ratio=round(stoploss_current_dist_ratio, 8), stoploss_current_dist_pct=round(stoploss_current_dist_ratio * 100, 2), diff --git a/freqtrade/rpc/telegram.py b/freqtrade/rpc/telegram.py index 19027f4d5..ced1bb5ca 100644 --- a/freqtrade/rpc/telegram.py +++ b/freqtrade/rpc/telegram.py @@ -606,9 +606,10 @@ class Telegram(RPCHandler): if r['is_open']: if r.get('realized_profit'): - lines.append( - "*Realized Profit:* `{realized_profit_ratio:.2%} ({realized_profit_r})`") - lines.append("*Total Profit:* `{total_profit_abs_r}` ") + lines.extend([ + "*Realized Profit:* `{realized_profit_ratio:.2%} ({realized_profit_r})`" + "*Total Profit:* `{total_profit_ratio:.2%} ({total_profit_abs_r})`" + ]) # Append empty line to improve readability lines.append(" ") diff --git a/tests/rpc/test_rpc.py b/tests/rpc/test_rpc.py index cd72da763..cf7d2bdeb 100644 --- a/tests/rpc/test_rpc.py +++ b/tests/rpc/test_rpc.py @@ -79,6 +79,7 @@ def test_rpc_trade_status(default_conf, ticker, fee, mocker) -> None: 'realized_profit_ratio': None, 'total_profit_abs': -4.09e-06, 'total_profit_fiat': ANY, + 'total_profit_ratio': ANY, 'exchange': 'binance', 'leverage': 1.0, 'interest_rate': 0.0, @@ -185,6 +186,7 @@ def test_rpc_trade_status(default_conf, ticker, fee, mocker) -> None: 'profit_pct': ANY, 'profit_abs': ANY, 'total_profit_abs': ANY, + 'total_profit_ratio': ANY, 'current_rate': ANY, }) assert results[0] == response_norate From cab1b750b35f4d356d64206c2b20aa2cb338f167 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 5 Mar 2023 19:45:04 +0100 Subject: [PATCH 103/229] Improve test accuracy --- freqtrade/rpc/rpc.py | 2 +- tests/rpc/test_rpc.py | 9 +++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 4b3f6209e..c68ed2d48 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -192,7 +192,7 @@ class RPC: current_profit = trade.close_profit or 0.0 current_profit_abs = trade.close_profit_abs or 0.0 total_profit_abs = trade.realized_profit + current_profit_abs - total_profit_ratio = 0.0 + total_profit_ratio: Optional[float] = None if trade.max_stake_amount: total_profit_ratio = ( (total_profit_abs / trade.max_stake_amount) * trade.leverage diff --git a/tests/rpc/test_rpc.py b/tests/rpc/test_rpc.py index cf7d2bdeb..1a1802c68 100644 --- a/tests/rpc/test_rpc.py +++ b/tests/rpc/test_rpc.py @@ -50,7 +50,7 @@ def test_rpc_trade_status(default_conf, ticker, fee, mocker) -> None: 'amount': 91.07468123, 'amount_requested': 91.07468124, 'stake_amount': 0.001, - 'max_stake_amount': ANY, + 'max_stake_amount': None, 'trade_duration': None, 'trade_duration_s': None, 'close_profit': None, @@ -79,7 +79,7 @@ def test_rpc_trade_status(default_conf, ticker, fee, mocker) -> None: 'realized_profit_ratio': None, 'total_profit_abs': -4.09e-06, 'total_profit_fiat': ANY, - 'total_profit_ratio': ANY, + 'total_profit_ratio': None, 'exchange': 'binance', 'leverage': 1.0, 'interest_rate': 0.0, @@ -169,6 +169,10 @@ def test_rpc_trade_status(default_conf, ticker, fee, mocker) -> None: results = rpc._rpc_trade_status() response = deepcopy(gen_response) + response.update({ + 'max_stake_amount': 0.001, + 'total_profit_ratio': pytest.approx(-0.00409), + }) assert results[0] == response mocker.patch(f'{EXMS}.get_rate', @@ -182,6 +186,7 @@ def test_rpc_trade_status(default_conf, ticker, fee, mocker) -> None: 'stoploss_current_dist': ANY, 'stoploss_current_dist_ratio': ANY, 'stoploss_current_dist_pct': ANY, + 'max_stake_amount': 0.001, 'profit_ratio': ANY, 'profit_pct': ANY, 'profit_abs': ANY, From c4a80e33ea3e647fab91efd4ace1c8de3f4afc6b Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 6 Mar 2023 07:01:17 +0100 Subject: [PATCH 104/229] Fix missing newline in telegram /status --- freqtrade/rpc/telegram.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/freqtrade/rpc/telegram.py b/freqtrade/rpc/telegram.py index ced1bb5ca..30aa55359 100644 --- a/freqtrade/rpc/telegram.py +++ b/freqtrade/rpc/telegram.py @@ -607,7 +607,7 @@ class Telegram(RPCHandler): if r['is_open']: if r.get('realized_profit'): lines.extend([ - "*Realized Profit:* `{realized_profit_ratio:.2%} ({realized_profit_r})`" + "*Realized Profit:* `{realized_profit_ratio:.2%} ({realized_profit_r})`", "*Total Profit:* `{total_profit_ratio:.2%} ({total_profit_abs_r})`" ]) From d779d60812f29553d029182e7b8b7907c2d5fea0 Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 6 Mar 2023 07:10:02 +0100 Subject: [PATCH 105/229] Expose total_profit_ratio through API --- freqtrade/rpc/api_server/api_schemas.py | 1 + freqtrade/rpc/api_server/api_v1.py | 3 ++- tests/rpc/test_rpc_apiserver.py | 1 + 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/freqtrade/rpc/api_server/api_schemas.py b/freqtrade/rpc/api_server/api_schemas.py index a751179b2..064a509fd 100644 --- a/freqtrade/rpc/api_server/api_schemas.py +++ b/freqtrade/rpc/api_server/api_schemas.py @@ -286,6 +286,7 @@ class OpenTradeSchema(TradeSchema): current_rate: float total_profit_abs: float total_profit_fiat: Optional[float] + total_profit_ratio: Optional[float] open_order: Optional[str] diff --git a/freqtrade/rpc/api_server/api_v1.py b/freqtrade/rpc/api_server/api_v1.py index f6bab3624..8ea70bb69 100644 --- a/freqtrade/rpc/api_server/api_v1.py +++ b/freqtrade/rpc/api_server/api_v1.py @@ -42,7 +42,8 @@ logger = logging.getLogger(__name__) # 2.22: Add FreqAI to backtesting # 2.23: Allow plot config request in webserver mode # 2.24: Add cancel_open_order endpoint -API_VERSION = 2.24 +# 2.25: Add several profit values to /status endpoint +API_VERSION = 2.25 # Public API, requires no auth. router_public = APIRouter() diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index e140a43f1..9c2c3ee3a 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -1012,6 +1012,7 @@ def test_api_status(botclient, mocker, ticker, fee, markets, is_short, 'profit_fiat': ANY, 'total_profit_abs': ANY, 'total_profit_fiat': ANY, + 'total_profit_ratio': ANY, 'realized_profit': 0.0, 'realized_profit_ratio': None, 'current_rate': current_rate, From 85e64cd1215b4ef2e0d323fe4be08db90d1d884c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 6 Mar 2023 07:21:23 +0000 Subject: [PATCH 106/229] Bump ccxt from 2.8.98 to 2.9.4 Bumps [ccxt](https://github.com/ccxt/ccxt) from 2.8.98 to 2.9.4. - [Release notes](https://github.com/ccxt/ccxt/releases) - [Changelog](https://github.com/ccxt/ccxt/blob/master/CHANGELOG.md) - [Commits](https://github.com/ccxt/ccxt/compare/2.8.98...2.9.4) --- updated-dependencies: - dependency-name: ccxt dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index a702507f9..c972ae1d4 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,7 +2,7 @@ numpy==1.24.2 pandas==1.5.3 pandas-ta==0.3.14b -ccxt==2.8.98 +ccxt==2.9.4 cryptography==39.0.2 aiohttp==3.8.4 SQLAlchemy==2.0.5.post1 From d9dc831772e67b3b04f26c9d160152c19940f5b9 Mon Sep 17 00:00:00 2001 From: robcaulk Date: Tue, 7 Mar 2023 11:33:54 +0100 Subject: [PATCH 107/229] allow user to drop ohlc from features in RL --- docs/freqai-parameter-table.md | 1 + docs/freqai-reinforcement-learning.md | 4 +++- freqtrade/constants.py | 1 + .../freqai/RL/BaseReinforcementLearningModel.py | 16 +++++++++------- tests/freqai/conftest.py | 4 +++- tests/freqai/test_freqai_interface.py | 8 +------- 6 files changed, 18 insertions(+), 16 deletions(-) diff --git a/docs/freqai-parameter-table.md b/docs/freqai-parameter-table.md index 275062a33..f67ea8541 100644 --- a/docs/freqai-parameter-table.md +++ b/docs/freqai-parameter-table.md @@ -84,6 +84,7 @@ Mandatory parameters are marked as **Required** and have to be set in one of the | `add_state_info` | Tell FreqAI to include state information in the feature set for training and inferencing. The current state variables include trade duration, current profit, trade position. This is only available in dry/live runs, and is automatically switched to false for backtesting.
**Datatype:** bool.
Default: `False`. | `net_arch` | Network architecture which is well described in [`stable_baselines3` doc](https://stable-baselines3.readthedocs.io/en/master/guide/custom_policy.html#examples). In summary: `[, dict(vf=[], pi=[])]`. By default this is set to `[128, 128]`, which defines 2 shared hidden layers with 128 units each. | `randomize_starting_position` | Randomize the starting point of each episode to avoid overfitting.
**Datatype:** bool.
Default: `False`. +| `drop_ohlc_from_features` | Do not include the normalized ohlc data in the feature set passed to the agent during training (ohlc will still be used for driving the environment in all cases)
**Datatype:** Boolean.
**Default:** `False` ### Additional parameters diff --git a/docs/freqai-reinforcement-learning.md b/docs/freqai-reinforcement-learning.md index 3810aec4e..04ca42a5d 100644 --- a/docs/freqai-reinforcement-learning.md +++ b/docs/freqai-reinforcement-learning.md @@ -176,9 +176,11 @@ As you begin to modify the strategy and the prediction model, you will quickly r factor = 100 + pair = self.pair.replace(':', '') + # you can use feature values from dataframe # Assumes the shifted RSI indicator has been generated in the strategy. - rsi_now = self.raw_features[f"%-rsi-period-10_shift-1_{self.pair}_" + rsi_now = self.raw_features[f"%-rsi-period-10_shift-1_{pair}_" f"{self.config['timeframe']}"].iloc[self._current_tick] # reward agent for entering trades diff --git a/freqtrade/constants.py b/freqtrade/constants.py index 1727da92e..46e9b5cd4 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -588,6 +588,7 @@ CONF_SCHEMA = { "rl_config": { "type": "object", "properties": { + "drop_ohlc_from_features": {"type": "boolean", "default": False}, "train_cycles": {"type": "integer"}, "max_trade_duration_candles": {"type": "integer"}, "add_state_info": {"type": "boolean", "default": False}, diff --git a/freqtrade/freqai/RL/BaseReinforcementLearningModel.py b/freqtrade/freqai/RL/BaseReinforcementLearningModel.py index a8ef69394..bac717f9f 100644 --- a/freqtrade/freqai/RL/BaseReinforcementLearningModel.py +++ b/freqtrade/freqai/RL/BaseReinforcementLearningModel.py @@ -114,6 +114,7 @@ class BaseReinforcementLearningModel(IFreqaiModel): # normalize all data based on train_dataset only prices_train, prices_test = self.build_ohlc_price_dataframes(dk.data_dictionary, pair, dk) + data_dictionary = dk.normalize_data(data_dictionary) # data cleaning/analysis @@ -148,12 +149,8 @@ class BaseReinforcementLearningModel(IFreqaiModel): env_info = self.pack_env_dict(dk.pair) - self.train_env = self.MyRLEnv(df=train_df, - prices=prices_train, - **env_info) - self.eval_env = Monitor(self.MyRLEnv(df=test_df, - prices=prices_test, - **env_info)) + self.train_env = self.MyRLEnv(df=train_df, prices=prices_train, **env_info) + self.eval_env = Monitor(self.MyRLEnv(df=test_df, prices=prices_test, **env_info)) self.eval_callback = EvalCallback(self.eval_env, deterministic=True, render=False, eval_freq=len(train_df), best_model_save_path=str(dk.data_path)) @@ -285,7 +282,6 @@ class BaseReinforcementLearningModel(IFreqaiModel): train_df = data_dictionary["train_features"] test_df = data_dictionary["test_features"] - # %-raw_volume_gen_shift-2_ETH/USDT_1h # price data for model training and evaluation tf = self.config['timeframe'] rename_dict = {'%-raw_open': 'open', '%-raw_low': 'low', @@ -318,6 +314,12 @@ class BaseReinforcementLearningModel(IFreqaiModel): prices_test.rename(columns=rename_dict, inplace=True) prices_test.reset_index(drop=True) + if self.rl_config["drop_ohlc_from_features"]: + train_df.drop(rename_dict.keys(), axis=1, inplace=True) + test_df.drop(rename_dict.keys(), axis=1, inplace=True) + feature_list = dk.training_features_list + feature_list = [e for e in feature_list if e not in rename_dict.keys()] + return prices_train, prices_test def load_model_from_disk(self, dk: FreqaiDataKitchen) -> Any: diff --git a/tests/freqai/conftest.py b/tests/freqai/conftest.py index 68e7ea49a..e140ee80b 100644 --- a/tests/freqai/conftest.py +++ b/tests/freqai/conftest.py @@ -78,7 +78,9 @@ def make_rl_config(conf): "rr": 1, "profit_aim": 0.02, "win_reward_factor": 2 - }} + }, + "drop_ohlc_from_features": False + } return conf diff --git a/tests/freqai/test_freqai_interface.py b/tests/freqai/test_freqai_interface.py index f8bee3659..3b370aea4 100644 --- a/tests/freqai/test_freqai_interface.py +++ b/tests/freqai/test_freqai_interface.py @@ -68,13 +68,6 @@ def test_extract_data_and_train_model_Standard(mocker, freqai_conf, model, pca, freqai_conf['freqai']['feature_parameters'].update({"shuffle_after_split": shuffle}) freqai_conf['freqai']['feature_parameters'].update({"buffer_train_data_candles": buffer}) - if 'ReinforcementLearner' in model: - model_save_ext = 'zip' - freqai_conf = make_rl_config(freqai_conf) - # test the RL guardrails - freqai_conf['freqai']['feature_parameters'].update({"use_SVM_to_remove_outliers": True}) - freqai_conf['freqai']['data_split_parameters'].update({'shuffle': True}) - if 'ReinforcementLearner' in model: model_save_ext = 'zip' freqai_conf = make_rl_config(freqai_conf) @@ -84,6 +77,7 @@ def test_extract_data_and_train_model_Standard(mocker, freqai_conf, model, pca, if 'test_3ac' in model or 'test_4ac' in model: freqai_conf["freqaimodel_path"] = str(Path(__file__).parents[1] / "freqai" / "test_models") + freqai_conf["freqai"]["rl_config"]["drop_ohlc_from_features"] = True strategy = get_patched_freqai_strategy(mocker, freqai_conf) exchange = get_patched_exchange(mocker, freqai_conf) From 2c7ae756f5b4576c7d393d09a6d57563d17be440 Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 8 Mar 2023 07:05:59 +0100 Subject: [PATCH 108/229] Improve mock behavior --- tests/optimize/test_backtest_detail.py | 2 +- tests/test_freqtradebot.py | 40 +++++++++++++------------- tests/test_integration.py | 2 +- 3 files changed, 22 insertions(+), 22 deletions(-) diff --git a/tests/optimize/test_backtest_detail.py b/tests/optimize/test_backtest_detail.py index ae06fca1d..2cb42c003 100644 --- a/tests/optimize/test_backtest_detail.py +++ b/tests/optimize/test_backtest_detail.py @@ -924,7 +924,7 @@ def test_backtest_results(default_conf, fee, mocker, caplog, data: BTContainer) mocker.patch(f"{EXMS}.get_fee", return_value=0.0) mocker.patch(f"{EXMS}.get_min_pair_stake_amount", return_value=0.00001) mocker.patch(f"{EXMS}.get_max_pair_stake_amount", return_value=float('inf')) - mocker.patch('freqtrade.exchange.binance.Binance.get_max_leverage', return_value=100) + mocker.patch(f"{EXMS}.get_max_leverage", return_value=100) patch_exchange(mocker) frame = _build_backtest_dataframe(data.data) backtesting = Backtesting(default_conf) diff --git a/tests/test_freqtradebot.py b/tests/test_freqtradebot.py index 5e9cca0f8..06832589c 100644 --- a/tests/test_freqtradebot.py +++ b/tests/test_freqtradebot.py @@ -1068,7 +1068,7 @@ def test_add_stoploss_on_exchange(mocker, default_conf_usdt, limit_order, is_sho mocker.patch(f'{EXMS}.get_trades_for_order', return_value=[]) stoploss = MagicMock(return_value={'id': 13434334}) - mocker.patch('freqtrade.exchange.binance.Binance.create_stoploss', stoploss) + mocker.patch(f'{EXMS}.create_stoploss', stoploss) freqtrade = FreqtradeBot(default_conf_usdt) freqtrade.strategy.order_types['stoploss_on_exchange'] = True @@ -1263,7 +1263,7 @@ def test_handle_sle_cancel_cant_recreate(mocker, default_conf_usdt, fee, caplog, get_fee=fee, ) mocker.patch.multiple( - 'freqtrade.exchange.binance.Binance', + EXMS, fetch_stoploss_order=MagicMock(return_value={'status': 'canceled', 'id': 100}), create_stoploss=MagicMock(side_effect=ExchangeError()), ) @@ -1307,7 +1307,7 @@ def test_create_stoploss_order_invalid_order( get_fee=fee, ) mocker.patch.multiple( - 'freqtrade.exchange.binance.Binance', + EXMS, fetch_order=MagicMock(return_value={'status': 'canceled'}), create_stoploss=MagicMock(side_effect=InvalidOrderException()), ) @@ -1360,7 +1360,7 @@ def test_create_stoploss_order_insufficient_funds( fetch_order=MagicMock(return_value={'status': 'canceled'}), ) mocker.patch.multiple( - 'freqtrade.exchange.binance.Binance', + EXMS, create_stoploss=MagicMock(side_effect=InsufficientFundsError()), ) patch_get_signal(freqtrade, enter_short=is_short, enter_long=not is_short) @@ -1410,7 +1410,7 @@ def test_handle_stoploss_on_exchange_trailing( get_fee=fee, ) mocker.patch.multiple( - 'freqtrade.exchange.binance.Binance', + EXMS, create_stoploss=stoploss, stoploss_adjust=MagicMock(return_value=True), ) @@ -1453,7 +1453,7 @@ def test_handle_stoploss_on_exchange_trailing( } }) - mocker.patch('freqtrade.exchange.binance.Binance.fetch_stoploss_order', stoploss_order_hanging) + mocker.patch(f'{EXMS}.fetch_stoploss_order', stoploss_order_hanging) # stoploss initially at 5% assert freqtrade.handle_trade(trade) is False @@ -1471,8 +1471,8 @@ def test_handle_stoploss_on_exchange_trailing( cancel_order_mock = MagicMock() stoploss_order_mock = MagicMock(return_value={'id': 'so1'}) - mocker.patch('freqtrade.exchange.binance.Binance.cancel_stoploss_order', cancel_order_mock) - mocker.patch('freqtrade.exchange.binance.Binance.create_stoploss', stoploss_order_mock) + mocker.patch(f'{EXMS}.cancel_stoploss_order', cancel_order_mock) + mocker.patch(f'{EXMS}.create_stoploss', stoploss_order_mock) # stoploss should not be updated as the interval is 60 seconds assert freqtrade.handle_trade(trade) is False @@ -1535,7 +1535,7 @@ def test_handle_stoploss_on_exchange_trailing_error( get_fee=fee, ) mocker.patch.multiple( - 'freqtrade.exchange.binance.Binance', + EXMS, create_stoploss=stoploss, stoploss_adjust=MagicMock(return_value=True), ) @@ -1573,9 +1573,9 @@ def test_handle_stoploss_on_exchange_trailing_error( 'stopPrice': '0.1' } } - mocker.patch('freqtrade.exchange.binance.Binance.cancel_stoploss_order', + mocker.patch(f'{EXMS}.cancel_stoploss_order', side_effect=InvalidOrderException()) - mocker.patch('freqtrade.exchange.binance.Binance.fetch_stoploss_order', + mocker.patch(f'{EXMS}.fetch_stoploss_order', return_value=stoploss_order_hanging) freqtrade.handle_trailing_stoploss_on_exchange(trade, stoploss_order_hanging) assert log_has_re(r"Could not cancel stoploss order abcd for pair ETH/USDT.*", caplog) @@ -1586,8 +1586,8 @@ def test_handle_stoploss_on_exchange_trailing_error( # Fail creating stoploss order trade.stoploss_last_update = arrow.utcnow().shift(minutes=-601).datetime caplog.clear() - cancel_mock = mocker.patch('freqtrade.exchange.binance.Binance.cancel_stoploss_order') - mocker.patch('freqtrade.exchange.binance.Binance.create_stoploss', side_effect=ExchangeError()) + cancel_mock = mocker.patch(f'{EXMS}.cancel_stoploss_order') + mocker.patch(f'{EXMS}.create_stoploss', side_effect=ExchangeError()) freqtrade.handle_trailing_stoploss_on_exchange(trade, stoploss_order_hanging) assert cancel_mock.call_count == 1 assert log_has_re(r"Could not create trailing stoploss order for pair ETH/USDT\..*", caplog) @@ -1604,7 +1604,7 @@ def test_stoploss_on_exchange_price_rounding( stoploss_mock = MagicMock(return_value={'id': '13434334'}) adjust_mock = MagicMock(return_value=False) mocker.patch.multiple( - 'freqtrade.exchange.binance.Binance', + EXMS, create_stoploss=stoploss_mock, stoploss_adjust=adjust_mock, price_to_precision=price_mock, @@ -1643,7 +1643,7 @@ def test_handle_stoploss_on_exchange_custom_stop( get_fee=fee, ) mocker.patch.multiple( - 'freqtrade.exchange.binance.Binance', + EXMS, create_stoploss=stoploss, stoploss_adjust=MagicMock(return_value=True), ) @@ -1686,7 +1686,7 @@ def test_handle_stoploss_on_exchange_custom_stop( } }) - mocker.patch('freqtrade.exchange.binance.Binance.fetch_stoploss_order', stoploss_order_hanging) + mocker.patch(f'{EXMS}.fetch_stoploss_order', stoploss_order_hanging) assert freqtrade.handle_trade(trade) is False assert freqtrade.handle_stoploss_on_exchange(trade) is False @@ -1703,8 +1703,8 @@ def test_handle_stoploss_on_exchange_custom_stop( cancel_order_mock = MagicMock() stoploss_order_mock = MagicMock(return_value={'id': 'so1'}) - mocker.patch('freqtrade.exchange.binance.Binance.cancel_stoploss_order', cancel_order_mock) - mocker.patch('freqtrade.exchange.binance.Binance.create_stoploss', stoploss_order_mock) + mocker.patch(f'{EXMS}.cancel_stoploss_order', cancel_order_mock) + mocker.patch(f'{EXMS}.create_stoploss', stoploss_order_mock) # stoploss should not be updated as the interval is 60 seconds assert freqtrade.handle_trade(trade) is False @@ -1821,7 +1821,7 @@ def test_tsl_on_exchange_compatible_with_edge(mocker, edge_conf, fee, limit_orde cancel_order_mock = MagicMock() stoploss_order_mock = MagicMock() mocker.patch(f'{EXMS}.cancel_stoploss_order', cancel_order_mock) - mocker.patch('freqtrade.exchange.binance.Binance.create_stoploss', stoploss_order_mock) + mocker.patch(f'{EXMS}.create_stoploss', stoploss_order_mock) # price goes down 5% mocker.patch(f'{EXMS}.fetch_ticker', MagicMock(return_value={ @@ -3660,7 +3660,7 @@ def test_may_execute_trade_exit_after_stoploss_on_exchange_hit( } }) - mocker.patch('freqtrade.exchange.binance.Binance.create_stoploss', stoploss) + mocker.patch(f'{EXMS}.create_stoploss', stoploss) freqtrade = FreqtradeBot(default_conf_usdt) freqtrade.strategy.order_types['stoploss_on_exchange'] = True diff --git a/tests/test_integration.py b/tests/test_integration.py index a3dd8d935..4c57c5669 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -56,9 +56,9 @@ def test_may_execute_exit_stoploss_on_exchange_multi(default_conf, ticker, fee, [ExitCheckTuple(exit_type=ExitType.EXIT_SIGNAL)]] ) cancel_order_mock = MagicMock() - mocker.patch('freqtrade.exchange.binance.Binance.create_stoploss', stoploss) mocker.patch.multiple( EXMS, + create_stoploss=stoploss, fetch_ticker=ticker, get_fee=fee, amount_to_precision=lambda s, x, y: y, From 29d337fa02be2aa6d79e8be49ea2d5b16c9f9cb9 Mon Sep 17 00:00:00 2001 From: robcaulk Date: Wed, 8 Mar 2023 11:26:28 +0100 Subject: [PATCH 109/229] ensure ohlc is dropped from both train and predict --- .../RL/BaseReinforcementLearningModel.py | 23 +++++++++++++++---- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/freqtrade/freqai/RL/BaseReinforcementLearningModel.py b/freqtrade/freqai/RL/BaseReinforcementLearningModel.py index bac717f9f..c528d8910 100644 --- a/freqtrade/freqai/RL/BaseReinforcementLearningModel.py +++ b/freqtrade/freqai/RL/BaseReinforcementLearningModel.py @@ -235,6 +235,9 @@ class BaseReinforcementLearningModel(IFreqaiModel): filtered_dataframe, _ = dk.filter_features( unfiltered_df, dk.training_features_list, training_filter=False ) + + filtered_dataframe = self.drop_ohlc_from_df(filtered_dataframe, dk) + filtered_dataframe = dk.normalize_data_from_metadata(filtered_dataframe) dk.data_dictionary["prediction_features"] = filtered_dataframe @@ -314,14 +317,24 @@ class BaseReinforcementLearningModel(IFreqaiModel): prices_test.rename(columns=rename_dict, inplace=True) prices_test.reset_index(drop=True) - if self.rl_config["drop_ohlc_from_features"]: - train_df.drop(rename_dict.keys(), axis=1, inplace=True) - test_df.drop(rename_dict.keys(), axis=1, inplace=True) - feature_list = dk.training_features_list - feature_list = [e for e in feature_list if e not in rename_dict.keys()] + train_df = self.drop_ohlc_from_df(train_df, dk) + test_df = self.drop_ohlc_from_df(test_df, dk) return prices_train, prices_test + def drop_ohlc_from_df(self, df: DataFrame, dk: FreqaiDataKitchen): + """ + Given a dataframe, drop the ohlc data + """ + drop_list = ['%-raw_open', '%-raw_low', '%-raw_high', '%-raw_close'] + + if self.rl_config["drop_ohlc_from_features"]: + df.drop(drop_list, axis=1, inplace=True) + feature_list = dk.training_features_list + feature_list = [e for e in feature_list if e not in drop_list] + + return df + def load_model_from_disk(self, dk: FreqaiDataKitchen) -> Any: """ Can be used by user if they are trying to limit_ram_usage *and* From 85e345fc4839292a88fee0e101e34551aa30e6ec Mon Sep 17 00:00:00 2001 From: Robert Caulk Date: Wed, 8 Mar 2023 19:29:39 +0100 Subject: [PATCH 110/229] Update BaseReinforcementLearningModel.py --- freqtrade/freqai/RL/BaseReinforcementLearningModel.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/freqtrade/freqai/RL/BaseReinforcementLearningModel.py b/freqtrade/freqai/RL/BaseReinforcementLearningModel.py index c528d8910..acdcf3135 100644 --- a/freqtrade/freqai/RL/BaseReinforcementLearningModel.py +++ b/freqtrade/freqai/RL/BaseReinforcementLearningModel.py @@ -330,8 +330,6 @@ class BaseReinforcementLearningModel(IFreqaiModel): if self.rl_config["drop_ohlc_from_features"]: df.drop(drop_list, axis=1, inplace=True) - feature_list = dk.training_features_list - feature_list = [e for e in feature_list if e not in drop_list] return df From 0318486bee485dc2951871d0b9c23909b1865a9f Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 8 Mar 2023 19:35:26 +0100 Subject: [PATCH 111/229] Update stoploss_from_open documentation for leverage adjustment --- docs/strategy-callbacks.md | 6 +++--- docs/strategy-customization.md | 6 ++++-- freqtrade/strategy/strategy_helper.py | 7 ++++--- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/docs/strategy-callbacks.md b/docs/strategy-callbacks.md index 81366c66e..f1cdc9f3b 100644 --- a/docs/strategy-callbacks.md +++ b/docs/strategy-callbacks.md @@ -316,11 +316,11 @@ class AwesomeStrategy(IStrategy): # evaluate highest to lowest, so that highest possible stop is used if current_profit > 0.40: - return stoploss_from_open(0.25, current_profit, is_short=trade.is_short) + return stoploss_from_open(0.25, current_profit, is_short=trade.is_short, leverage=trade.leverage) elif current_profit > 0.25: - return stoploss_from_open(0.15, current_profit, is_short=trade.is_short) + return stoploss_from_open(0.15, current_profit, is_short=trade.is_short, leverage=trade.leverage) elif current_profit > 0.20: - return stoploss_from_open(0.07, current_profit, is_short=trade.is_short) + return stoploss_from_open(0.07, current_profit, is_short=trade.is_short, leverage=trade.leverage) # return maximum stoploss value, keeping current stoploss price unchanged return 1 diff --git a/docs/strategy-customization.md b/docs/strategy-customization.md index 3519a80cd..8ab0b1464 100644 --- a/docs/strategy-customization.md +++ b/docs/strategy-customization.md @@ -881,7 +881,7 @@ All columns of the informative dataframe will be available on the returning data ### *stoploss_from_open()* -Stoploss values returned from `custom_stoploss` must specify a percentage relative to `current_rate`, but sometimes you may want to specify a stoploss relative to the open price instead. `stoploss_from_open()` is a helper function to calculate a stoploss value that can be returned from `custom_stoploss` which will be equivalent to the desired percentage above the open price. +Stoploss values returned from `custom_stoploss` must specify a percentage relative to `current_rate`, but sometimes you may want to specify a stoploss relative to the entry point instead. `stoploss_from_open()` is a helper function to calculate a stoploss value that can be returned from `custom_stoploss` which will be equivalent to the desired trade profit above the entry point. ??? Example "Returning a stoploss relative to the open price from the custom stoploss function" @@ -889,6 +889,8 @@ Stoploss values returned from `custom_stoploss` must specify a percentage relati If we want a stop price at 7% above the open price we can call `stoploss_from_open(0.07, current_profit, False)` which will return `0.1157024793`. 11.57% below $121 is $107, which is the same as 7% above $100. + This function will consider leverage - so at 10x leverage, the actual stoploss would be 0.7% above $100 (0.7% * 10x = 7%). + ``` python @@ -907,7 +909,7 @@ Stoploss values returned from `custom_stoploss` must specify a percentage relati # once the profit has risen above 10%, keep the stoploss at 7% above the open price if current_profit > 0.10: - return stoploss_from_open(0.07, current_profit, is_short=trade.is_short) + return stoploss_from_open(0.07, current_profit, is_short=trade.is_short, leverage=trade.leverage) return 1 diff --git a/freqtrade/strategy/strategy_helper.py b/freqtrade/strategy/strategy_helper.py index 3ba1850b3..27ebe7e69 100644 --- a/freqtrade/strategy/strategy_helper.py +++ b/freqtrade/strategy/strategy_helper.py @@ -90,17 +90,18 @@ def stoploss_from_open( leverage: float = 1.0 ) -> float: """ - - Given the current profit, and a desired stop loss value relative to the open price, + Given the current profit, and a desired stop loss value relative to the trade entry price, return a stop loss value that is relative to the current price, and which can be returned from `custom_stoploss`. The requested stop can be positive for a stop above the open price, or negative for a stop below the open price. The return value is always >= 0. + `open_relative_stop` will be considered as adjusted for leverage if leverage is provided.. Returns 0 if the resulting stop price would be above/below (longs/shorts) the current price - :param open_relative_stop: Desired stop loss percentage relative to open price + :param open_relative_stop: Desired stop loss percentage, relative to the open price, + adjusted for leverage :param current_profit: The current profit percentage :param is_short: When true, perform the calculation for short instead of long :param leverage: Leverage to use for the calculation From d10ee0979a0fd9349b5ad1e2d6ba03e3c3d3104f Mon Sep 17 00:00:00 2001 From: robcaulk Date: Wed, 8 Mar 2023 19:37:11 +0100 Subject: [PATCH 112/229] ensure training_features_list is updated properly --- freqtrade/freqai/RL/BaseReinforcementLearningModel.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/freqtrade/freqai/RL/BaseReinforcementLearningModel.py b/freqtrade/freqai/RL/BaseReinforcementLearningModel.py index acdcf3135..e10880f46 100644 --- a/freqtrade/freqai/RL/BaseReinforcementLearningModel.py +++ b/freqtrade/freqai/RL/BaseReinforcementLearningModel.py @@ -330,6 +330,8 @@ class BaseReinforcementLearningModel(IFreqaiModel): if self.rl_config["drop_ohlc_from_features"]: df.drop(drop_list, axis=1, inplace=True) + feature_list = dk.training_features_list + dk.training_features_list = [e for e in feature_list if e not in drop_list] return df From 30fd1e742efead96b3ae12fa75b44d1be7231560 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 9 Mar 2023 07:14:54 +0000 Subject: [PATCH 113/229] Add 3.8 block for strategyUpdater --- freqtrade/commands/strategy_utils_commands.py | 4 ++++ tests/test_strategy_updater.py | 8 ++++++++ 2 files changed, 12 insertions(+) diff --git a/freqtrade/commands/strategy_utils_commands.py b/freqtrade/commands/strategy_utils_commands.py index aca368742..ed4d0bf1a 100644 --- a/freqtrade/commands/strategy_utils_commands.py +++ b/freqtrade/commands/strategy_utils_commands.py @@ -1,4 +1,5 @@ import logging +import sys import time from pathlib import Path from typing import Any, Dict @@ -19,6 +20,9 @@ def start_strategy_update(args: Dict[str, Any]) -> None: :return: None """ + if sys.version_info == (3, 8): # pragma: no cover + sys.exit("Freqtrade strategy updater requires Python version >= 3.9") + config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE) strategy_objs = StrategyResolver.search_all_objects( diff --git a/tests/test_strategy_updater.py b/tests/test_strategy_updater.py index 927c5e99f..ea971af72 100644 --- a/tests/test_strategy_updater.py +++ b/tests/test_strategy_updater.py @@ -1,8 +1,16 @@ # pragma pylint: disable=missing-docstring, protected-access, invalid-name +import sys + +import pytest + from freqtrade.strategy.strategyupdater import StrategyUpdater +if sys.version_info < (3, 9): + pytest.skip("StrategyUpdater is not compatible with Python 3.8", allow_module_level=True) + + def test_strategy_updater(default_conf, caplog) -> None: instance_strategy_updater = StrategyUpdater() modified_code1 = instance_strategy_updater.update_code(""" From d3a3ddbc614609a63a0fbea827d635b3673f59aa Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 9 Mar 2023 19:42:43 +0100 Subject: [PATCH 114/229] Check if exchang provides bid/ask via fetch_tickers - and fail with spread filter if it doesn't. closes #8286 --- freqtrade/exchange/exchange.py | 1 + freqtrade/exchange/gate.py | 1 + freqtrade/plugins/pairlist/SpreadFilter.py | 7 +++++++ tests/plugins/test_pairlist.py | 6 ++++++ 4 files changed, 15 insertions(+) diff --git a/freqtrade/exchange/exchange.py b/freqtrade/exchange/exchange.py index cdbda1506..c0e07c6d7 100644 --- a/freqtrade/exchange/exchange.py +++ b/freqtrade/exchange/exchange.py @@ -69,6 +69,7 @@ class Exchange: # Check https://github.com/ccxt/ccxt/issues/10767 for removal of ohlcv_volume_currency "ohlcv_volume_currency": "base", # "base" or "quote" "tickers_have_quoteVolume": True, + "tickers_have_bid_ask": True, # bid / ask empty for fetch_tickers "tickers_have_price": True, "trades_pagination": "time", # Possible are "time" or "id" "trades_pagination_arg": "since", diff --git a/freqtrade/exchange/gate.py b/freqtrade/exchange/gate.py index 80ed4088a..03b568460 100644 --- a/freqtrade/exchange/gate.py +++ b/freqtrade/exchange/gate.py @@ -32,6 +32,7 @@ class Gate(Exchange): _ft_has_futures: Dict = { "needs_trading_fees": True, + "tickers_have_bid_ask": False, "fee_cost_in_contracts": False, # Set explicitly to false for clarity "order_props_in_contracts": ['amount', 'filled', 'remaining'], "stop_price_type_field": "price_type", diff --git a/freqtrade/plugins/pairlist/SpreadFilter.py b/freqtrade/plugins/pairlist/SpreadFilter.py index 207328d08..d47b68568 100644 --- a/freqtrade/plugins/pairlist/SpreadFilter.py +++ b/freqtrade/plugins/pairlist/SpreadFilter.py @@ -5,6 +5,7 @@ import logging from typing import Any, Dict, Optional from freqtrade.constants import Config +from freqtrade.exceptions import OperationalException from freqtrade.exchange.types import Ticker from freqtrade.plugins.pairlist.IPairList import IPairList @@ -22,6 +23,12 @@ class SpreadFilter(IPairList): self._max_spread_ratio = pairlistconfig.get('max_spread_ratio', 0.005) self._enabled = self._max_spread_ratio != 0 + if not self._exchange.get_option('tickers_have_bid_ask'): + raise OperationalException( + f"{self.name} requires exchange to have bid/ask data for tickers, " + "which is not available for the selected exchange / trading mode." + ) + @property def needstickers(self) -> bool: """ diff --git a/tests/plugins/test_pairlist.py b/tests/plugins/test_pairlist.py index 40a3871d7..18ee365e2 100644 --- a/tests/plugins/test_pairlist.py +++ b/tests/plugins/test_pairlist.py @@ -828,6 +828,12 @@ def test_pair_whitelist_not_supported_Spread(mocker, default_conf, tickers) -> N match=r'Exchange does not support fetchTickers, .*'): get_patched_freqtradebot(mocker, default_conf) + mocker.patch(f'{EXMS}.exchange_has', MagicMock(return_value=True)) + mocker.patch(f'{EXMS}.get_option', MagicMock(return_value=False)) + with pytest.raises(OperationalException, + match=r'.*requires exchange to have bid/ask data'): + get_patched_freqtradebot(mocker, default_conf) + @pytest.mark.parametrize("pairlist", TESTABLE_PAIRLISTS) def test_pairlist_class(mocker, whitelist_conf, markets, pairlist): From bfc7f48f17c82b759e8a012e372b3ee92017263a Mon Sep 17 00:00:00 2001 From: hippocritical Date: Fri, 10 Mar 2023 08:59:07 +0100 Subject: [PATCH 115/229] added checks for python3.8 or lower since ast_comments.unparse() needs python 3.9 or higher. testing with python 3.8 would make the build fail tests, skipping it there. --- freqtrade/commands/strategy_utils_commands.py | 47 ++-- tests/test_strategy_updater.py | 227 +++++++++--------- 2 files changed, 143 insertions(+), 131 deletions(-) diff --git a/freqtrade/commands/strategy_utils_commands.py b/freqtrade/commands/strategy_utils_commands.py index aca368742..56a28cf65 100644 --- a/freqtrade/commands/strategy_utils_commands.py +++ b/freqtrade/commands/strategy_utils_commands.py @@ -1,4 +1,5 @@ import logging +import sys import time from pathlib import Path from typing import Any, Dict @@ -19,28 +20,34 @@ def start_strategy_update(args: Dict[str, Any]) -> None: :return: None """ - config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE) + if sys.version_info <= (3, 8): + print("This code requires Python 3.9 or higher. " + "We cannot continue. " + "Please upgrade your python version to use this command.") - strategy_objs = StrategyResolver.search_all_objects( - config, enum_failed=False, recursive=config.get('recursive_strategy_search', False)) - - filtered_strategy_objs = [] - if 'strategy_list' in args: - for args_strategy in args['strategy_list']: - for strategy_obj in strategy_objs: - if (strategy_obj['name'] == args_strategy - and strategy_obj not in filtered_strategy_objs): - filtered_strategy_objs.append(strategy_obj) - break - - for filtered_strategy_obj in filtered_strategy_objs: - start_conversion(filtered_strategy_obj, config) else: - processed_locations = set() - for strategy_obj in strategy_objs: - if strategy_obj['location'] not in processed_locations: - processed_locations.add(strategy_obj['location']) - start_conversion(strategy_obj, config) + config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE) + + strategy_objs = StrategyResolver.search_all_objects( + config, enum_failed=False, recursive=config.get('recursive_strategy_search', False)) + + filtered_strategy_objs = [] + if 'strategy_list' in args: + for args_strategy in args['strategy_list']: + for strategy_obj in strategy_objs: + if (strategy_obj['name'] == args_strategy + and strategy_obj not in filtered_strategy_objs): + filtered_strategy_objs.append(strategy_obj) + break + + for filtered_strategy_obj in filtered_strategy_objs: + start_conversion(filtered_strategy_obj, config) + else: + processed_locations = set() + for strategy_obj in strategy_objs: + if strategy_obj['location'] not in processed_locations: + processed_locations.add(strategy_obj['location']) + start_conversion(strategy_obj, config) def start_conversion(strategy_obj, config): diff --git a/tests/test_strategy_updater.py b/tests/test_strategy_updater.py index 927c5e99f..3831c2ee6 100644 --- a/tests/test_strategy_updater.py +++ b/tests/test_strategy_updater.py @@ -1,130 +1,135 @@ # pragma pylint: disable=missing-docstring, protected-access, invalid-name +import sys + from freqtrade.strategy.strategyupdater import StrategyUpdater def test_strategy_updater(default_conf, caplog) -> None: - instance_strategy_updater = StrategyUpdater() - modified_code1 = instance_strategy_updater.update_code(""" -class testClass(IStrategy): - def populate_buy_trend(): - pass - def populate_sell_trend(): - pass - def check_buy_timeout(): - pass - def check_sell_timeout(): - pass - def custom_sell(): - pass -""") - modified_code2 = instance_strategy_updater.update_code(""" -ticker_interval = '15m' -buy_some_parameter = IntParameter(space='buy') -sell_some_parameter = IntParameter(space='sell') -""") - modified_code3 = instance_strategy_updater.update_code(""" -use_sell_signal = True -sell_profit_only = True -sell_profit_offset = True -ignore_roi_if_buy_signal = True -forcebuy_enable = True -""") - modified_code4 = instance_strategy_updater.update_code(""" -dataframe.loc[reduce(lambda x, y: x & y, conditions), ["buy", "buy_tag"]] = (1, "buy_signal_1") -dataframe.loc[reduce(lambda x, y: x & y, conditions), 'sell'] = 1 -""") - modified_code5 = instance_strategy_updater.update_code(""" -def confirm_trade_exit(sell_reason: str): - pass + if sys.version_info <= (3, 8): + print("skipped tests since python version is 3.8 or lower.") + else: + instance_strategy_updater = StrategyUpdater() + modified_code1 = instance_strategy_updater.update_code(""" + class testClass(IStrategy): + def populate_buy_trend(): + pass + def populate_sell_trend(): + pass + def check_buy_timeout(): + pass + def check_sell_timeout(): + pass + def custom_sell(): + pass """) - modified_code6 = instance_strategy_updater.update_code(""" -order_time_in_force = { - 'buy': 'gtc', - 'sell': 'ioc' -} -order_types = { - 'buy': 'limit', - 'sell': 'market', - 'stoploss': 'market', - 'stoploss_on_exchange': False -} -unfilledtimeout = { - 'buy': 1, - 'sell': 2 -} -""") - - modified_code7 = instance_strategy_updater.update_code(""" -def confirm_trade_exit(sell_reason): - if (sell_reason == 'stop_loss'): + modified_code2 = instance_strategy_updater.update_code(""" + ticker_interval = '15m' + buy_some_parameter = IntParameter(space='buy') + sell_some_parameter = IntParameter(space='sell') + """) + modified_code3 = instance_strategy_updater.update_code(""" + use_sell_signal = True + sell_profit_only = True + sell_profit_offset = True + ignore_roi_if_buy_signal = True + forcebuy_enable = True + """) + modified_code4 = instance_strategy_updater.update_code(""" + dataframe.loc[reduce(lambda x, y: x & y, conditions), ["buy", "buy_tag"]] = (1, "buy_signal_1") + dataframe.loc[reduce(lambda x, y: x & y, conditions), 'sell'] = 1 + """) + modified_code5 = instance_strategy_updater.update_code(""" + def confirm_trade_exit(sell_reason: str): pass -""") - modified_code8 = instance_strategy_updater.update_code(""" -sell_reason == 'sell_signal' -sell_reason == 'force_sell' -sell_reason == 'emergency_sell' -""") - modified_code9 = instance_strategy_updater.update_code(""" -# This is the 1st comment -import talib.abstract as ta -# This is the 2nd comment -import freqtrade.vendor.qtpylib.indicators as qtpylib - - -class someStrategy(IStrategy): - # This is the 3rd comment - # This attribute will be overridden if the config file contains "minimal_roi" - minimal_roi = { - "0": 0.50 + """) + modified_code6 = instance_strategy_updater.update_code(""" + order_time_in_force = { + 'buy': 'gtc', + 'sell': 'ioc' } + order_types = { + 'buy': 'limit', + 'sell': 'market', + 'stoploss': 'market', + 'stoploss_on_exchange': False + } + unfilledtimeout = { + 'buy': 1, + 'sell': 2 + } + """) - # This is the 4th comment - stoploss = -0.1 -""") - # currently still missing: - # Webhook terminology, Telegram notification settings, Strategy/Config settings + modified_code7 = instance_strategy_updater.update_code(""" + def confirm_trade_exit(sell_reason): + if (sell_reason == 'stop_loss'): + pass + """) + modified_code8 = instance_strategy_updater.update_code(""" + sell_reason == 'sell_signal' + sell_reason == 'force_sell' + sell_reason == 'emergency_sell' + """) + modified_code9 = instance_strategy_updater.update_code(""" + # This is the 1st comment + import talib.abstract as ta + # This is the 2nd comment + import freqtrade.vendor.qtpylib.indicators as qtpylib - assert "populate_entry_trend" in modified_code1 - assert "populate_exit_trend" in modified_code1 - assert "check_entry_timeout" in modified_code1 - assert "check_exit_timeout" in modified_code1 - assert "custom_exit" in modified_code1 - assert "INTERFACE_VERSION = 3" in modified_code1 - assert "timeframe" in modified_code2 - # check for not editing hyperopt spaces - assert "space='buy'" in modified_code2 - assert "space='sell'" in modified_code2 + class someStrategy(IStrategy): + # This is the 3rd comment + # This attribute will be overridden if the config file contains "minimal_roi" + minimal_roi = { + "0": 0.50 + } - assert "use_exit_signal" in modified_code3 - assert "exit_profit_only" in modified_code3 - assert "exit_profit_offset" in modified_code3 - assert "ignore_roi_if_entry_signal" in modified_code3 - assert "force_entry_enable" in modified_code3 + # This is the 4th comment + stoploss = -0.1 + """) + # currently still missing: + # Webhook terminology, Telegram notification settings, Strategy/Config settings - assert "enter_long" in modified_code4 - assert "exit_long" in modified_code4 - assert "enter_tag" in modified_code4 + assert "populate_entry_trend" in modified_code1 + assert "populate_exit_trend" in modified_code1 + assert "check_entry_timeout" in modified_code1 + assert "check_exit_timeout" in modified_code1 + assert "custom_exit" in modified_code1 + assert "INTERFACE_VERSION = 3" in modified_code1 - assert "exit_reason" in modified_code5 + assert "timeframe" in modified_code2 + # check for not editing hyperopt spaces + assert "space='buy'" in modified_code2 + assert "space='sell'" in modified_code2 - assert "'entry': 'gtc'" in modified_code6 - assert "'exit': 'ioc'" in modified_code6 - assert "'entry': 'limit'" in modified_code6 - assert "'exit': 'market'" in modified_code6 - assert "'entry': 1" in modified_code6 - assert "'exit': 2" in modified_code6 + assert "use_exit_signal" in modified_code3 + assert "exit_profit_only" in modified_code3 + assert "exit_profit_offset" in modified_code3 + assert "ignore_roi_if_entry_signal" in modified_code3 + assert "force_entry_enable" in modified_code3 - assert "exit_reason" in modified_code7 - assert "exit_reason == 'stop_loss'" in modified_code7 + assert "enter_long" in modified_code4 + assert "exit_long" in modified_code4 + assert "enter_tag" in modified_code4 - # those tests currently don't work, next in line. - assert "exit_signal" in modified_code8 - assert "exit_reason" in modified_code8 - assert "force_exit" in modified_code8 - assert "emergency_exit" in modified_code8 + assert "exit_reason" in modified_code5 - assert "This is the 1st comment" in modified_code9 - assert "This is the 2nd comment" in modified_code9 - assert "This is the 3rd comment" in modified_code9 + assert "'entry': 'gtc'" in modified_code6 + assert "'exit': 'ioc'" in modified_code6 + assert "'entry': 'limit'" in modified_code6 + assert "'exit': 'market'" in modified_code6 + assert "'entry': 1" in modified_code6 + assert "'exit': 2" in modified_code6 + + assert "exit_reason" in modified_code7 + assert "exit_reason == 'stop_loss'" in modified_code7 + + # those tests currently don't work, next in line. + assert "exit_signal" in modified_code8 + assert "exit_reason" in modified_code8 + assert "force_exit" in modified_code8 + assert "emergency_exit" in modified_code8 + + assert "This is the 1st comment" in modified_code9 + assert "This is the 2nd comment" in modified_code9 + assert "This is the 3rd comment" in modified_code9 From a3988f56b28ddef95fd425e9804d3154491ad994 Mon Sep 17 00:00:00 2001 From: hippocritical Date: Fri, 10 Mar 2023 09:23:56 +0100 Subject: [PATCH 116/229] Sorry matthias, did not see that you already committed something and did overwrite you. Added your version to it instead of mine and pushed again (since it was already overwritten by me). --- freqtrade/commands/strategy_utils_commands.py | 45 ++-- tests/test_strategy_updater.py | 232 +++++++++--------- 2 files changed, 138 insertions(+), 139 deletions(-) diff --git a/freqtrade/commands/strategy_utils_commands.py b/freqtrade/commands/strategy_utils_commands.py index 56a28cf65..ed4d0bf1a 100644 --- a/freqtrade/commands/strategy_utils_commands.py +++ b/freqtrade/commands/strategy_utils_commands.py @@ -20,34 +20,31 @@ def start_strategy_update(args: Dict[str, Any]) -> None: :return: None """ - if sys.version_info <= (3, 8): - print("This code requires Python 3.9 or higher. " - "We cannot continue. " - "Please upgrade your python version to use this command.") + if sys.version_info == (3, 8): # pragma: no cover + sys.exit("Freqtrade strategy updater requires Python version >= 3.9") - else: - config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE) + config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE) - strategy_objs = StrategyResolver.search_all_objects( - config, enum_failed=False, recursive=config.get('recursive_strategy_search', False)) + strategy_objs = StrategyResolver.search_all_objects( + config, enum_failed=False, recursive=config.get('recursive_strategy_search', False)) - filtered_strategy_objs = [] - if 'strategy_list' in args: - for args_strategy in args['strategy_list']: - for strategy_obj in strategy_objs: - if (strategy_obj['name'] == args_strategy - and strategy_obj not in filtered_strategy_objs): - filtered_strategy_objs.append(strategy_obj) - break - - for filtered_strategy_obj in filtered_strategy_objs: - start_conversion(filtered_strategy_obj, config) - else: - processed_locations = set() + filtered_strategy_objs = [] + if 'strategy_list' in args: + for args_strategy in args['strategy_list']: for strategy_obj in strategy_objs: - if strategy_obj['location'] not in processed_locations: - processed_locations.add(strategy_obj['location']) - start_conversion(strategy_obj, config) + if (strategy_obj['name'] == args_strategy + and strategy_obj not in filtered_strategy_objs): + filtered_strategy_objs.append(strategy_obj) + break + + for filtered_strategy_obj in filtered_strategy_objs: + start_conversion(filtered_strategy_obj, config) + else: + processed_locations = set() + for strategy_obj in strategy_objs: + if strategy_obj['location'] not in processed_locations: + processed_locations.add(strategy_obj['location']) + start_conversion(strategy_obj, config) def start_conversion(strategy_obj, config): diff --git a/tests/test_strategy_updater.py b/tests/test_strategy_updater.py index 3831c2ee6..26d173871 100644 --- a/tests/test_strategy_updater.py +++ b/tests/test_strategy_updater.py @@ -2,134 +2,136 @@ import sys +import pytest + from freqtrade.strategy.strategyupdater import StrategyUpdater def test_strategy_updater(default_conf, caplog) -> None: - if sys.version_info <= (3, 8): - print("skipped tests since python version is 3.8 or lower.") - else: - instance_strategy_updater = StrategyUpdater() - modified_code1 = instance_strategy_updater.update_code(""" - class testClass(IStrategy): - def populate_buy_trend(): - pass - def populate_sell_trend(): - pass - def check_buy_timeout(): - pass - def check_sell_timeout(): - pass - def custom_sell(): - pass - """) - modified_code2 = instance_strategy_updater.update_code(""" - ticker_interval = '15m' - buy_some_parameter = IntParameter(space='buy') - sell_some_parameter = IntParameter(space='sell') - """) - modified_code3 = instance_strategy_updater.update_code(""" - use_sell_signal = True - sell_profit_only = True - sell_profit_offset = True - ignore_roi_if_buy_signal = True - forcebuy_enable = True - """) - modified_code4 = instance_strategy_updater.update_code(""" - dataframe.loc[reduce(lambda x, y: x & y, conditions), ["buy", "buy_tag"]] = (1, "buy_signal_1") - dataframe.loc[reduce(lambda x, y: x & y, conditions), 'sell'] = 1 - """) - modified_code5 = instance_strategy_updater.update_code(""" - def confirm_trade_exit(sell_reason: str): + if sys.version_info < (3, 9): + pytest.skip("StrategyUpdater is not compatible with Python 3.8", allow_module_level=True) + + instance_strategy_updater = StrategyUpdater() + modified_code1 = instance_strategy_updater.update_code(""" +class testClass(IStrategy): + def populate_buy_trend(): pass - """) - modified_code6 = instance_strategy_updater.update_code(""" - order_time_in_force = { - 'buy': 'gtc', - 'sell': 'ioc' + def populate_sell_trend(): + pass + def check_buy_timeout(): + pass + def check_sell_timeout(): + pass + def custom_sell(): + pass +""") + modified_code2 = instance_strategy_updater.update_code(""" +ticker_interval = '15m' +buy_some_parameter = IntParameter(space='buy') +sell_some_parameter = IntParameter(space='sell') +""") + modified_code3 = instance_strategy_updater.update_code(""" +use_sell_signal = True +sell_profit_only = True +sell_profit_offset = True +ignore_roi_if_buy_signal = True +forcebuy_enable = True +""") + modified_code4 = instance_strategy_updater.update_code(""" +dataframe.loc[reduce(lambda x, y: x & y, conditions), ["buy", "buy_tag"]] = (1, "buy_signal_1") +dataframe.loc[reduce(lambda x, y: x & y, conditions), 'sell'] = 1 +""") + modified_code5 = instance_strategy_updater.update_code(""" +def confirm_trade_exit(sell_reason: str): + pass + """) + modified_code6 = instance_strategy_updater.update_code(""" +order_time_in_force = { + 'buy': 'gtc', + 'sell': 'ioc' +} +order_types = { + 'buy': 'limit', + 'sell': 'market', + 'stoploss': 'market', + 'stoploss_on_exchange': False +} +unfilledtimeout = { + 'buy': 1, + 'sell': 2 +} +""") + + modified_code7 = instance_strategy_updater.update_code(""" +def confirm_trade_exit(sell_reason): + if (sell_reason == 'stop_loss'): + pass +""") + modified_code8 = instance_strategy_updater.update_code(""" +sell_reason == 'sell_signal' +sell_reason == 'force_sell' +sell_reason == 'emergency_sell' +""") + modified_code9 = instance_strategy_updater.update_code(""" +# This is the 1st comment +import talib.abstract as ta +# This is the 2nd comment +import freqtrade.vendor.qtpylib.indicators as qtpylib + + +class someStrategy(IStrategy): + # This is the 3rd comment + # This attribute will be overridden if the config file contains "minimal_roi" + minimal_roi = { + "0": 0.50 } - order_types = { - 'buy': 'limit', - 'sell': 'market', - 'stoploss': 'market', - 'stoploss_on_exchange': False - } - unfilledtimeout = { - 'buy': 1, - 'sell': 2 - } - """) - modified_code7 = instance_strategy_updater.update_code(""" - def confirm_trade_exit(sell_reason): - if (sell_reason == 'stop_loss'): - pass - """) - modified_code8 = instance_strategy_updater.update_code(""" - sell_reason == 'sell_signal' - sell_reason == 'force_sell' - sell_reason == 'emergency_sell' - """) - modified_code9 = instance_strategy_updater.update_code(""" - # This is the 1st comment - import talib.abstract as ta - # This is the 2nd comment - import freqtrade.vendor.qtpylib.indicators as qtpylib + # This is the 4th comment + stoploss = -0.1 +""") + # currently still missing: + # Webhook terminology, Telegram notification settings, Strategy/Config settings + assert "populate_entry_trend" in modified_code1 + assert "populate_exit_trend" in modified_code1 + assert "check_entry_timeout" in modified_code1 + assert "check_exit_timeout" in modified_code1 + assert "custom_exit" in modified_code1 + assert "INTERFACE_VERSION = 3" in modified_code1 - class someStrategy(IStrategy): - # This is the 3rd comment - # This attribute will be overridden if the config file contains "minimal_roi" - minimal_roi = { - "0": 0.50 - } + assert "timeframe" in modified_code2 + # check for not editing hyperopt spaces + assert "space='buy'" in modified_code2 + assert "space='sell'" in modified_code2 - # This is the 4th comment - stoploss = -0.1 - """) - # currently still missing: - # Webhook terminology, Telegram notification settings, Strategy/Config settings + assert "use_exit_signal" in modified_code3 + assert "exit_profit_only" in modified_code3 + assert "exit_profit_offset" in modified_code3 + assert "ignore_roi_if_entry_signal" in modified_code3 + assert "force_entry_enable" in modified_code3 - assert "populate_entry_trend" in modified_code1 - assert "populate_exit_trend" in modified_code1 - assert "check_entry_timeout" in modified_code1 - assert "check_exit_timeout" in modified_code1 - assert "custom_exit" in modified_code1 - assert "INTERFACE_VERSION = 3" in modified_code1 + assert "enter_long" in modified_code4 + assert "exit_long" in modified_code4 + assert "enter_tag" in modified_code4 - assert "timeframe" in modified_code2 - # check for not editing hyperopt spaces - assert "space='buy'" in modified_code2 - assert "space='sell'" in modified_code2 + assert "exit_reason" in modified_code5 - assert "use_exit_signal" in modified_code3 - assert "exit_profit_only" in modified_code3 - assert "exit_profit_offset" in modified_code3 - assert "ignore_roi_if_entry_signal" in modified_code3 - assert "force_entry_enable" in modified_code3 + assert "'entry': 'gtc'" in modified_code6 + assert "'exit': 'ioc'" in modified_code6 + assert "'entry': 'limit'" in modified_code6 + assert "'exit': 'market'" in modified_code6 + assert "'entry': 1" in modified_code6 + assert "'exit': 2" in modified_code6 - assert "enter_long" in modified_code4 - assert "exit_long" in modified_code4 - assert "enter_tag" in modified_code4 + assert "exit_reason" in modified_code7 + assert "exit_reason == 'stop_loss'" in modified_code7 - assert "exit_reason" in modified_code5 + # those tests currently don't work, next in line. + assert "exit_signal" in modified_code8 + assert "exit_reason" in modified_code8 + assert "force_exit" in modified_code8 + assert "emergency_exit" in modified_code8 - assert "'entry': 'gtc'" in modified_code6 - assert "'exit': 'ioc'" in modified_code6 - assert "'entry': 'limit'" in modified_code6 - assert "'exit': 'market'" in modified_code6 - assert "'entry': 1" in modified_code6 - assert "'exit': 2" in modified_code6 - - assert "exit_reason" in modified_code7 - assert "exit_reason == 'stop_loss'" in modified_code7 - - # those tests currently don't work, next in line. - assert "exit_signal" in modified_code8 - assert "exit_reason" in modified_code8 - assert "force_exit" in modified_code8 - assert "emergency_exit" in modified_code8 - - assert "This is the 1st comment" in modified_code9 - assert "This is the 2nd comment" in modified_code9 - assert "This is the 3rd comment" in modified_code9 + assert "This is the 1st comment" in modified_code9 + assert "This is the 2nd comment" in modified_code9 + assert "This is the 3rd comment" in modified_code9 From a76ca771f8c557a6a596f7b7c0cbb748f6418ade Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 10 Mar 2023 18:00:20 +0100 Subject: [PATCH 117/229] telegram: Fix sending telegram message with exception --- freqtrade/enums/rpcmessagetype.py | 1 + freqtrade/freqtradebot.py | 4 ++-- freqtrade/rpc/telegram.py | 3 +++ freqtrade/rpc/webhook.py | 1 + freqtrade/worker.py | 7 +++++-- 5 files changed, 12 insertions(+), 4 deletions(-) diff --git a/freqtrade/enums/rpcmessagetype.py b/freqtrade/enums/rpcmessagetype.py index 404c75401..16d81b1d8 100644 --- a/freqtrade/enums/rpcmessagetype.py +++ b/freqtrade/enums/rpcmessagetype.py @@ -4,6 +4,7 @@ from enum import Enum class RPCMessageType(str, Enum): STATUS = 'status' WARNING = 'warning' + EXCEPTION = 'exception' STARTUP = 'startup' ENTRY = 'entry' diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index cec7176f6..feb0baf5a 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -133,13 +133,13 @@ class FreqtradeBot(LoggingMixin): # Initialize protections AFTER bot start - otherwise parameters are not loaded. self.protections = ProtectionManager(self.config, self.strategy.protections) - def notify_status(self, msg: str) -> None: + def notify_status(self, msg: str, msg_type=RPCMessageType.STATUS) -> None: """ Public method for users of this class (worker, etc.) to send notifications via RPC about changes in the bot status. """ self.rpc.send_msg({ - 'type': RPCMessageType.STATUS, + 'type': msg_type, 'status': msg }) diff --git a/freqtrade/rpc/telegram.py b/freqtrade/rpc/telegram.py index 30aa55359..0c0b24f00 100644 --- a/freqtrade/rpc/telegram.py +++ b/freqtrade/rpc/telegram.py @@ -414,6 +414,9 @@ class Telegram(RPCHandler): elif msg_type == RPCMessageType.WARNING: message = f"\N{WARNING SIGN} *Warning:* `{msg['status']}`" + elif msg_type == RPCMessageType.EXCEPTION: + # Errors will contain exceptions, which are wrapped in tripple ticks. + message = f"\N{WARNING SIGN} *ERROR:* \n {msg['status']}" elif msg_type == RPCMessageType.STARTUP: message = f"{msg['status']}" diff --git a/freqtrade/rpc/webhook.py b/freqtrade/rpc/webhook.py index d81d8d24f..0967de70d 100644 --- a/freqtrade/rpc/webhook.py +++ b/freqtrade/rpc/webhook.py @@ -58,6 +58,7 @@ class Webhook(RPCHandler): valuedict = whconfig.get('webhookexitcancel') elif msg['type'] in (RPCMessageType.STATUS, RPCMessageType.STARTUP, + RPCMessageType.EXCEPTION, RPCMessageType.WARNING): valuedict = whconfig.get('webhookstatus') elif msg['type'].value in whconfig: diff --git a/freqtrade/worker.py b/freqtrade/worker.py index 388163678..fb89e7a2d 100644 --- a/freqtrade/worker.py +++ b/freqtrade/worker.py @@ -12,7 +12,7 @@ import sdnotify from freqtrade import __version__ from freqtrade.configuration import Configuration from freqtrade.constants import PROCESS_THROTTLE_SECS, RETRY_TIMEOUT, Config -from freqtrade.enums import State +from freqtrade.enums import RPCMessageType, State from freqtrade.exceptions import OperationalException, TemporaryError from freqtrade.exchange import timeframe_to_next_date from freqtrade.freqtradebot import FreqtradeBot @@ -185,7 +185,10 @@ class Worker: tb = traceback.format_exc() hint = 'Issue `/start` if you think it is safe to restart.' - self.freqtrade.notify_status(f'OperationalException:\n```\n{tb}```{hint}') + self.freqtrade.notify_status( + f'*OperationalException:*\n```\n{tb}```\n {hint}', + msg_type=RPCMessageType.EXCEPTION + ) logger.exception('OperationalException. Stopping trader ...') self.freqtrade.state = State.STOPPED From a2336f256bda321f54172693335a8dcdafad9e3f Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 11 Mar 2023 08:25:45 +0100 Subject: [PATCH 118/229] Add profit descriptions closes #8234 --- docs/bot-basics.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/bot-basics.md b/docs/bot-basics.md index 925fc7862..1aa8f3085 100644 --- a/docs/bot-basics.md +++ b/docs/bot-basics.md @@ -12,6 +12,9 @@ This page provides you some basic concepts on how Freqtrade works and operates. * **Indicators**: Technical indicators (SMA, EMA, RSI, ...). * **Limit order**: Limit orders which execute at the defined limit price or better. * **Market order**: Guaranteed to fill, may move price depending on the order size. +* **Current Profit**: Currently pending (unrealized) profit for this trade. This is mainly used throughout the bot and UI. +* **Realized Profit**: Already realized profit. Only relevant in combination with [partial exits](strategy-callbacks.md#adjust-trade-position) - which also explains the calculation logic for this. +* **Total Profit**: Combined realized and unrealized profit. The relative number (%) is calculated against the total investment in this trade. ## Fee handling From 39c651e40c9d9f83b4dd2c58e82a17488b475a0c Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 11 Mar 2023 15:03:06 +0100 Subject: [PATCH 119/229] Remove pointless reset of close_profit --- freqtrade/freqtradebot.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index feb0baf5a..281d90432 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -1468,8 +1468,6 @@ class FreqtradeBot(LoggingMixin): return False trade.close_rate = None trade.close_rate_requested = None - trade.close_profit = None - trade.close_profit_abs = None # Set exit_reason for fill message exit_reason_prev = trade.exit_reason trade.exit_reason = trade.exit_reason + f", {reason}" if trade.exit_reason else reason From 59d2ff3ffabe55dfeb35b820c9376bf4e5ec32b0 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 11 Mar 2023 15:12:32 +0100 Subject: [PATCH 120/229] Simplify `handle_cancel_exit ` --- freqtrade/freqtradebot.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index 281d90432..3924b111f 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -1460,32 +1460,32 @@ class FreqtradeBot(LoggingMixin): return False try: - co = self.exchange.cancel_order_with_result(order['id'], trade.pair, - trade.amount) + order = self.exchange.cancel_order_with_result(order['id'], trade.pair, + trade.amount) except InvalidOrderException: logger.exception( f"Could not cancel {trade.exit_side} order {trade.open_order_id}") return False - trade.close_rate = None - trade.close_rate_requested = None + # Set exit_reason for fill message exit_reason_prev = trade.exit_reason trade.exit_reason = trade.exit_reason + f", {reason}" if trade.exit_reason else reason - self.update_trade_state(trade, trade.open_order_id, co) # Order might be filled above in odd timing issues. - if co.get('status') in ('canceled', 'cancelled'): + if order.get('status') in ('canceled', 'cancelled'): trade.exit_reason = None - trade.open_order_id = None else: trade.exit_reason = exit_reason_prev - - logger.info(f'{trade.exit_side.capitalize()} order {reason} for {trade}.') cancelled = True else: reason = constants.CANCEL_REASON['CANCELLED_ON_EXCHANGE'] - logger.info(f'{trade.exit_side.capitalize()} order {reason} for {trade}.') - self.update_trade_state(trade, trade.open_order_id, order) - trade.open_order_id = None + trade.exit_reason = None + + self.update_trade_state(trade, trade.open_order_id, order) + + logger.info(f'{trade.exit_side.capitalize()} order {reason} for {trade}.') + trade.open_order_id = None + trade.close_rate = None + trade.close_rate_requested = None self._notify_exit_cancel( trade, From 8726a4645d7fc69bb2c9120bb49b039db60fb142 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 11 Mar 2023 15:15:32 +0100 Subject: [PATCH 121/229] Don't use deprecated Type construct --- freqtrade/misc.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/freqtrade/misc.py b/freqtrade/misc.py index 87cea54c0..0cd5c6ffd 100644 --- a/freqtrade/misc.py +++ b/freqtrade/misc.py @@ -6,8 +6,7 @@ import logging import re from datetime import datetime from pathlib import Path -from typing import Any, Dict, Iterator, List, Mapping, Optional, Union -from typing.io import IO +from typing import Any, Dict, Iterator, List, Mapping, Optional, TextIO, Union from urllib.parse import urlparse import orjson @@ -103,7 +102,7 @@ def file_dump_joblib(filename: Path, data: Any, log: bool = True) -> None: logger.debug(f'done joblib dump to "{filename}"') -def json_load(datafile: IO) -> Any: +def json_load(datafile: Union[gzip.GzipFile, TextIO]) -> Any: """ load data with rapidjson Use this to have a consistent experience, From b23841fbfedc970c1dc706f5ea057f1143babba4 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 11 Mar 2023 17:35:30 +0100 Subject: [PATCH 122/229] Bump ccxt to 2.9.12 --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index c972ae1d4..5977a6440 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,7 +2,7 @@ numpy==1.24.2 pandas==1.5.3 pandas-ta==0.3.14b -ccxt==2.9.4 +ccxt==2.9.12 cryptography==39.0.2 aiohttp==3.8.4 SQLAlchemy==2.0.5.post1 From 82cb107520d2709afde40f40c342590f3d860a1b Mon Sep 17 00:00:00 2001 From: initrv Date: Sun, 12 Mar 2023 01:32:55 +0300 Subject: [PATCH 123/229] add tensorboard category --- docs/freqai-reinforcement-learning.md | 4 ++-- freqtrade/freqai/RL/Base3ActionRLEnv.py | 2 +- freqtrade/freqai/RL/Base4ActionRLEnv.py | 2 +- freqtrade/freqai/RL/Base5ActionRLEnv.py | 2 +- freqtrade/freqai/RL/BaseEnvironment.py | 21 ++++++++++++------- freqtrade/freqai/RL/TensorboardCallback.py | 14 ++++++------- .../prediction_models/ReinforcementLearner.py | 2 +- 7 files changed, 26 insertions(+), 21 deletions(-) diff --git a/docs/freqai-reinforcement-learning.md b/docs/freqai-reinforcement-learning.md index 04ca42a5d..ed6a41825 100644 --- a/docs/freqai-reinforcement-learning.md +++ b/docs/freqai-reinforcement-learning.md @@ -248,13 +248,13 @@ FreqAI also provides a built in episodic summary logger called `self.tensorboard """ def calculate_reward(self, action: int) -> float: if not self._is_valid(action): - self.tensorboard_log("is_valid") + self.tensorboard_log("invalid") return -2 ``` !!! Note - The `self.tensorboard_log()` function is designed for tracking incremented objects only i.e. events, actions inside the training environment. If the event of interest is a float, the float can be passed as the second argument e.g. `self.tensorboard_log("float_metric1", 0.23)` would add 0.23 to `float_metric`. In this case you can also disable incrementing using `inc=False` parameter. + The `self.tensorboard_log()` function is designed for tracking incremented objects only i.e. events, actions inside the training environment. If the event of interest is a float, the float can be passed as the second argument e.g. `self.tensorboard_log("float_metric1", 0.23)`. In this case the metric values are not incremented. ### Choosing a base environment diff --git a/freqtrade/freqai/RL/Base3ActionRLEnv.py b/freqtrade/freqai/RL/Base3ActionRLEnv.py index 3b5fffc58..a108d776e 100644 --- a/freqtrade/freqai/RL/Base3ActionRLEnv.py +++ b/freqtrade/freqai/RL/Base3ActionRLEnv.py @@ -47,7 +47,7 @@ class Base3ActionRLEnv(BaseEnvironment): self._update_unrealized_total_profit() step_reward = self.calculate_reward(action) self.total_reward += step_reward - self.tensorboard_log(self.actions._member_names_[action]) + self.tensorboard_log(self.actions._member_names_[action], category="actions") trade_type = None if self.is_tradesignal(action): diff --git a/freqtrade/freqai/RL/Base4ActionRLEnv.py b/freqtrade/freqai/RL/Base4ActionRLEnv.py index 8f45028b1..4f093f06c 100644 --- a/freqtrade/freqai/RL/Base4ActionRLEnv.py +++ b/freqtrade/freqai/RL/Base4ActionRLEnv.py @@ -48,7 +48,7 @@ class Base4ActionRLEnv(BaseEnvironment): self._update_unrealized_total_profit() step_reward = self.calculate_reward(action) self.total_reward += step_reward - self.tensorboard_log(self.actions._member_names_[action]) + self.tensorboard_log(self.actions._member_names_[action], category="actions") trade_type = None if self.is_tradesignal(action): diff --git a/freqtrade/freqai/RL/Base5ActionRLEnv.py b/freqtrade/freqai/RL/Base5ActionRLEnv.py index 22d3cae30..490ef3601 100644 --- a/freqtrade/freqai/RL/Base5ActionRLEnv.py +++ b/freqtrade/freqai/RL/Base5ActionRLEnv.py @@ -49,7 +49,7 @@ class Base5ActionRLEnv(BaseEnvironment): self._update_unrealized_total_profit() step_reward = self.calculate_reward(action) self.total_reward += step_reward - self.tensorboard_log(self.actions._member_names_[action]) + self.tensorboard_log(self.actions._member_names_[action], category="actions") trade_type = None if self.is_tradesignal(action): diff --git a/freqtrade/freqai/RL/BaseEnvironment.py b/freqtrade/freqai/RL/BaseEnvironment.py index 7a4467bf7..df2a89d81 100644 --- a/freqtrade/freqai/RL/BaseEnvironment.py +++ b/freqtrade/freqai/RL/BaseEnvironment.py @@ -137,7 +137,8 @@ class BaseEnvironment(gym.Env): self.np_random, seed = seeding.np_random(seed) return [seed] - def tensorboard_log(self, metric: str, value: Union[int, float] = 1, inc: bool = True): + def tensorboard_log(self, metric: str, value: Optional[Union[int, float]] = None, + category: str = "custom"): """ Function builds the tensorboard_metrics dictionary to be parsed by the TensorboardCallback. This @@ -149,17 +150,23 @@ class BaseEnvironment(gym.Env): def calculate_reward(self, action: int) -> float: if not self._is_valid(action): - self.tensorboard_log("is_valid") + self.tensorboard_log("invalid") return -2 :param metric: metric to be tracked and incremented - :param value: value to increment `metric` by - :param inc: sets whether the `value` is incremented or not + :param value: `metric` value + :param category: `metric` category """ - if not inc or metric not in self.tensorboard_metrics: - self.tensorboard_metrics[metric] = value + increment = True if not value else False + value = 1 if increment else value + + if category not in self.tensorboard_metrics: + self.tensorboard_metrics[category] = {} + + if not increment or metric not in self.tensorboard_metrics[category]: + self.tensorboard_metrics[category][metric] = value else: - self.tensorboard_metrics[metric] += value + self.tensorboard_metrics[category][metric] += value def reset_tensorboard_log(self): self.tensorboard_metrics = {} diff --git a/freqtrade/freqai/RL/TensorboardCallback.py b/freqtrade/freqai/RL/TensorboardCallback.py index b596742e9..1828319cd 100644 --- a/freqtrade/freqai/RL/TensorboardCallback.py +++ b/freqtrade/freqai/RL/TensorboardCallback.py @@ -46,14 +46,12 @@ class TensorboardCallback(BaseCallback): local_info = self.locals["infos"][0] tensorboard_metrics = self.training_env.get_attr("tensorboard_metrics")[0] - for info in local_info: - if info not in ["episode", "terminal_observation"]: - self.logger.record(f"_info/{info}", local_info[info]) + for metric in local_info: + if metric not in ["episode", "terminal_observation"]: + self.logger.record(f"info/{metric}", local_info[metric]) - for info in tensorboard_metrics: - if info in [action.name for action in self.actions]: - self.logger.record(f"_actions/{info}", tensorboard_metrics[info]) - else: - self.logger.record(f"_custom/{info}", tensorboard_metrics[info]) + for category in tensorboard_metrics: + for metric in tensorboard_metrics[category]: + self.logger.record(f"{category}/{metric}", tensorboard_metrics[category][metric]) return True diff --git a/freqtrade/freqai/prediction_models/ReinforcementLearner.py b/freqtrade/freqai/prediction_models/ReinforcementLearner.py index 2a87151f9..e795703d4 100644 --- a/freqtrade/freqai/prediction_models/ReinforcementLearner.py +++ b/freqtrade/freqai/prediction_models/ReinforcementLearner.py @@ -100,7 +100,7 @@ class ReinforcementLearner(BaseReinforcementLearningModel): """ # first, penalize if the action is not valid if not self._is_valid(action): - self.tensorboard_log("is_valid") + self.tensorboard_log("invalid", category="actions") return -2 pnl = self.get_unrealized_profit() From aa283a04478075a331d64f9fff1f2f310575c463 Mon Sep 17 00:00:00 2001 From: froggleston Date: Sun, 12 Mar 2023 12:44:12 +0000 Subject: [PATCH 124/229] Fix None limit on pair_candles RPC call --- scripts/rest_client.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/scripts/rest_client.py b/scripts/rest_client.py index 144d428e5..6c8e13f2c 100755 --- a/scripts/rest_client.py +++ b/scripts/rest_client.py @@ -340,12 +340,14 @@ class FtRestClient(): :param limit: Limit result to the last n candles. :return: json object """ - return self._get("pair_candles", params={ + params = { "pair": pair, "timeframe": timeframe, - "limit": limit, - }) - + } + if limit: + params['limit'] = limit + return self._get("pair_candles", params=params) + def pair_history(self, pair, timeframe, strategy, timerange=None): """Return historic, analyzed dataframe From 5bfee44bba51b0005ec126583ff343d073ba897c Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 12 Mar 2023 15:24:27 +0100 Subject: [PATCH 125/229] Whitespace fix --- scripts/rest_client.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/rest_client.py b/scripts/rest_client.py index 6c8e13f2c..196542780 100755 --- a/scripts/rest_client.py +++ b/scripts/rest_client.py @@ -347,7 +347,7 @@ class FtRestClient(): if limit: params['limit'] = limit return self._get("pair_candles", params=params) - + def pair_history(self, pair, timeframe, strategy, timerange=None): """Return historic, analyzed dataframe From cb086f79ff263e075dc8cb7fcd841059b7153082 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 12 Mar 2023 15:46:34 +0100 Subject: [PATCH 126/229] Improve doc wording and command parameters --- docs/utils.md | 47 ++++++++++++++++++++++++++++----- freqtrade/commands/arguments.py | 2 +- requirements.txt | 2 +- 3 files changed, 43 insertions(+), 8 deletions(-) diff --git a/docs/utils.md b/docs/utils.md index 3d6eda3ce..eb675442f 100644 --- a/docs/utils.md +++ b/docs/utils.md @@ -947,6 +947,7 @@ Common arguments: --userdir PATH, --user-data-dir PATH Path to userdata directory. ``` + ### Examples Print trades with id 2 and 3 as json @@ -956,11 +957,45 @@ freqtrade show-trades --db-url sqlite:///tradesv3.sqlite --trade-ids 2 3 --print ``` ### Strategy-Updater -Updates a list strategies or all strategies within the strategies folder to be v3 compliant including futures. -If the command runs without --strategy-list then all files inside the strategies folder will be converted. -``` -usage: freqtrade strategy_updater -optional arguments: - --strategy-list defines a list of strategies that should be converted +Updates listed strategies or all strategies within the strategies folder to be v3 compliant. +If the command runs without --strategy-list then all strategies inside the strategies folder will be converted. +Your original strategy will remain available in the `user_data/strategies_orig_updater/` directory. + +!!! Warning "Conversion results" + Strategy updater will work on a "best effort" approach. Please do your due diligence and verify the results of the conversion. + We also recommend to run a python formatter (e.g. `black`) to format results in a sane manner. + +``` +usage: freqtrade strategy-updater [-h] [-v] [--logfile FILE] [-V] [-c PATH] + [-d PATH] [--userdir PATH] + [--strategy-list STRATEGY_LIST [STRATEGY_LIST ...]] + +options: + -h, --help show this help message and exit + --strategy-list STRATEGY_LIST [STRATEGY_LIST ...] + Provide a space-separated list of strategies to + backtest. Please note that timeframe needs to be set + either in config or via command line. When using this + together with `--export trades`, the strategy-name is + injected into the filename (so `backtest-data.json` + becomes `backtest-data-SampleStrategy.json` + +Common arguments: + -v, --verbose Verbose mode (-vv for more, -vvv to get all messages). + --logfile FILE, --log-file FILE + Log to the file specified. Special values are: + 'syslog', 'journald'. See the documentation for more + details. + -V, --version show program's version number and exit + -c PATH, --config PATH + Specify configuration file (default: + `userdir/config.json` or `config.json` whichever + exists). Multiple --config options may be used. Can be + set to `-` to read config from stdin. + -d PATH, --datadir PATH, --data-dir PATH + Path to directory with historical backtesting data. + --userdir PATH, --user-data-dir PATH + Path to userdata directory. + ``` diff --git a/freqtrade/commands/arguments.py b/freqtrade/commands/arguments.py index a3cdc378a..9b714a864 100644 --- a/freqtrade/commands/arguments.py +++ b/freqtrade/commands/arguments.py @@ -116,7 +116,7 @@ NO_CONF_REQURIED = ["convert-data", "convert-trade-data", "download-data", "list NO_CONF_ALLOWED = ["create-userdir", "list-exchanges", "new-strategy"] -ARGS_STRATEGY_UTILS = ARGS_COMMON_OPTIMIZE + ["strategy_list"] +ARGS_STRATEGY_UTILS = ["strategy_list"] class Arguments: diff --git a/requirements.txt b/requirements.txt index 7607a3664..a0ff8e03a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -56,4 +56,4 @@ schedule==1.1.0 websockets==10.4 janus==1.0.0 -ast-comments>=1.0.0 +ast-comments==1.0.0 From d2a412d2c65ee34576ac06638748700bb3ee4e03 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 12 Mar 2023 15:47:03 +0100 Subject: [PATCH 127/229] Simplify start_strategy_update --- freqtrade/commands/strategy_utils_commands.py | 30 ++++++++----------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/freqtrade/commands/strategy_utils_commands.py b/freqtrade/commands/strategy_utils_commands.py index ed4d0bf1a..e579ec475 100644 --- a/freqtrade/commands/strategy_utils_commands.py +++ b/freqtrade/commands/strategy_utils_commands.py @@ -29,31 +29,27 @@ def start_strategy_update(args: Dict[str, Any]) -> None: config, enum_failed=False, recursive=config.get('recursive_strategy_search', False)) filtered_strategy_objs = [] - if 'strategy_list' in args: - for args_strategy in args['strategy_list']: - for strategy_obj in strategy_objs: - if (strategy_obj['name'] == args_strategy - and strategy_obj not in filtered_strategy_objs): - filtered_strategy_objs.append(strategy_obj) - break + if args['strategy_list']: + filtered_strategy_objs = [ + strategy_obj for strategy_obj in strategy_objs + if strategy_obj['name'] in args['strategy_list'] + ] - for filtered_strategy_obj in filtered_strategy_objs: - start_conversion(filtered_strategy_obj, config) else: - processed_locations = set() - for strategy_obj in strategy_objs: - if strategy_obj['location'] not in processed_locations: - processed_locations.add(strategy_obj['location']) - start_conversion(strategy_obj, config) + # Use all available entries. + filtered_strategy_objs = strategy_objs + + processed_locations = set() + for strategy_obj in filtered_strategy_objs: + if strategy_obj['location'] not in processed_locations: + processed_locations.add(strategy_obj['location']) + start_conversion(strategy_obj, config) def start_conversion(strategy_obj, config): - # try: print(f"Conversion of {Path(strategy_obj['location']).name} started.") instance_strategy_updater = StrategyUpdater() start = time.perf_counter() instance_strategy_updater.start(config, strategy_obj) elapsed = time.perf_counter() - start print(f"Conversion of {Path(strategy_obj['location']).name} took {elapsed:.1f} seconds.") - # except: - # pass From 0911cd72a2fb2ed5fd87c6d3f7ad3eb2706edb6d Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 12 Mar 2023 15:59:02 +0100 Subject: [PATCH 128/229] Add test for strategy-updater start method --- freqtrade/commands/arguments.py | 2 +- tests/commands/test_commands.py | 37 ++++++++++++++++++++++++++++++++- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/freqtrade/commands/arguments.py b/freqtrade/commands/arguments.py index 9b714a864..47aa37fdf 100644 --- a/freqtrade/commands/arguments.py +++ b/freqtrade/commands/arguments.py @@ -116,7 +116,7 @@ NO_CONF_REQURIED = ["convert-data", "convert-trade-data", "download-data", "list NO_CONF_ALLOWED = ["create-userdir", "list-exchanges", "new-strategy"] -ARGS_STRATEGY_UTILS = ["strategy_list"] +ARGS_STRATEGY_UTILS = ["strategy_list", "strategy_path", "recursive_strategy_search"] class Arguments: diff --git a/tests/commands/test_commands.py b/tests/commands/test_commands.py index 0ba1924a7..179712c6d 100644 --- a/tests/commands/test_commands.py +++ b/tests/commands/test_commands.py @@ -14,7 +14,8 @@ from freqtrade.commands import (start_backtesting_show, start_convert_data, star start_hyperopt_show, start_install_ui, start_list_data, start_list_exchanges, start_list_markets, start_list_strategies, start_list_timeframes, start_new_strategy, start_show_trades, - start_test_pairlist, start_trading, start_webserver) + start_strategy_update, start_test_pairlist, start_trading, + start_webserver) from freqtrade.commands.db_commands import start_convert_db from freqtrade.commands.deploy_commands import (clean_ui_subdir, download_and_install_ui, get_ui_download_url, read_ui_version) @@ -1546,3 +1547,37 @@ def test_start_convert_db(mocker, fee, tmpdir, caplog): start_convert_db(pargs) assert db_target_file.is_file() + + +def test_start_strategy_updater(mocker, tmpdir): + sc_mock = mocker.patch('freqtrade.commands.strategy_utils_commands.start_conversion') + teststrats = Path(__file__).parent.parent / 'strategy/strats' + args = [ + "strategy-updater", + "--userdir", + str(tmpdir), + "--strategy-path", + str(teststrats), + ] + pargs = get_args(args) + pargs['config'] = None + start_strategy_update(pargs) + # Number of strategies in the test directory + assert sc_mock.call_count == 11 + + sc_mock.reset_mock() + args = [ + "strategy-updater", + "--userdir", + str(tmpdir), + "--strategy-path", + str(teststrats), + "--strategy-list", + "StrategyTestV3", + "StrategyTestV2" + ] + pargs = get_args(args) + pargs['config'] = None + start_strategy_update(pargs) + # Number of strategies in the test directory + assert sc_mock.call_count == 2 From b5c4f9ebe293097c08554e06c785a3e40ed993b1 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 12 Mar 2023 16:26:12 +0100 Subject: [PATCH 129/229] Split updater_tests to be clearer --- tests/test_strategy_updater.py | 139 ++++++++++++++++++++------------- 1 file changed, 86 insertions(+), 53 deletions(-) diff --git a/tests/test_strategy_updater.py b/tests/test_strategy_updater.py index 26d173871..7205a609d 100644 --- a/tests/test_strategy_updater.py +++ b/tests/test_strategy_updater.py @@ -7,9 +7,11 @@ import pytest from freqtrade.strategy.strategyupdater import StrategyUpdater -def test_strategy_updater(default_conf, caplog) -> None: - if sys.version_info < (3, 9): - pytest.skip("StrategyUpdater is not compatible with Python 3.8", allow_module_level=True) +if sys.version_info < (3, 9): + pytest.skip("StrategyUpdater is not compatible with Python 3.8", allow_module_level=True) + + +def test_strategy_updater_methods(default_conf, caplog) -> None: instance_strategy_updater = StrategyUpdater() modified_code1 = instance_strategy_updater.update_code(""" @@ -25,11 +27,32 @@ class testClass(IStrategy): def custom_sell(): pass """) + + assert "populate_entry_trend" in modified_code1 + assert "populate_exit_trend" in modified_code1 + assert "check_entry_timeout" in modified_code1 + assert "check_exit_timeout" in modified_code1 + assert "custom_exit" in modified_code1 + assert "INTERFACE_VERSION = 3" in modified_code1 + + +def test_strategy_updater_params(default_conf, caplog) -> None: + instance_strategy_updater = StrategyUpdater() + modified_code2 = instance_strategy_updater.update_code(""" ticker_interval = '15m' buy_some_parameter = IntParameter(space='buy') sell_some_parameter = IntParameter(space='sell') """) + + assert "timeframe" in modified_code2 + # check for not editing hyperopt spaces + assert "space='buy'" in modified_code2 + assert "space='sell'" in modified_code2 + + +def test_strategy_updater_constants(default_conf, caplog) -> None: + instance_strategy_updater = StrategyUpdater() modified_code3 = instance_strategy_updater.update_code(""" use_sell_signal = True sell_profit_only = True @@ -37,15 +60,38 @@ sell_profit_offset = True ignore_roi_if_buy_signal = True forcebuy_enable = True """) - modified_code4 = instance_strategy_updater.update_code(""" + + assert "use_exit_signal" in modified_code3 + assert "exit_profit_only" in modified_code3 + assert "exit_profit_offset" in modified_code3 + assert "ignore_roi_if_entry_signal" in modified_code3 + assert "force_entry_enable" in modified_code3 + + +def test_strategy_updater_df_columns(default_conf, caplog) -> None: + instance_strategy_updater = StrategyUpdater() + modified_code = instance_strategy_updater.update_code(""" dataframe.loc[reduce(lambda x, y: x & y, conditions), ["buy", "buy_tag"]] = (1, "buy_signal_1") dataframe.loc[reduce(lambda x, y: x & y, conditions), 'sell'] = 1 """) - modified_code5 = instance_strategy_updater.update_code(""" + + assert "enter_long" in modified_code + assert "exit_long" in modified_code + assert "enter_tag" in modified_code + + +def test_strategy_updater_method_params(default_conf, caplog) -> None: + instance_strategy_updater = StrategyUpdater() + modified_code = instance_strategy_updater.update_code(""" def confirm_trade_exit(sell_reason: str): pass """) - modified_code6 = instance_strategy_updater.update_code(""" + assert "exit_reason" in modified_code + + +def test_strategy_updater_dicts(default_conf, caplog) -> None: + instance_strategy_updater = StrategyUpdater() + modified_code = instance_strategy_updater.update_code(""" order_time_in_force = { 'buy': 'gtc', 'sell': 'ioc' @@ -62,17 +108,44 @@ unfilledtimeout = { } """) - modified_code7 = instance_strategy_updater.update_code(""" + assert "'entry': 'gtc'" in modified_code + assert "'exit': 'ioc'" in modified_code + assert "'entry': 'limit'" in modified_code + assert "'exit': 'market'" in modified_code + assert "'entry': 1" in modified_code + assert "'exit': 2" in modified_code + + +def test_strategy_updater_comparisons(default_conf, caplog) -> None: + instance_strategy_updater = StrategyUpdater() + modified_code = instance_strategy_updater.update_code(""" def confirm_trade_exit(sell_reason): if (sell_reason == 'stop_loss'): pass """) - modified_code8 = instance_strategy_updater.update_code(""" + assert "exit_reason" in modified_code + assert "exit_reason == 'stop_loss'" in modified_code + + +def test_strategy_updater_strings(default_conf, caplog) -> None: + instance_strategy_updater = StrategyUpdater() + + modified_code = instance_strategy_updater.update_code(""" sell_reason == 'sell_signal' sell_reason == 'force_sell' sell_reason == 'emergency_sell' """) - modified_code9 = instance_strategy_updater.update_code(""" + + # those tests currently don't work, next in line. + assert "exit_signal" in modified_code + assert "exit_reason" in modified_code + assert "force_exit" in modified_code + assert "emergency_exit" in modified_code + + +def test_strategy_updater_comments(default_conf, caplog) -> None: + instance_strategy_updater = StrategyUpdater() + modified_code = instance_strategy_updater.update_code(""" # This is the 1st comment import talib.abstract as ta # This is the 2nd comment @@ -89,49 +162,9 @@ class someStrategy(IStrategy): # This is the 4th comment stoploss = -0.1 """) + + assert "This is the 1st comment" in modified_code + assert "This is the 2nd comment" in modified_code + assert "This is the 3rd comment" in modified_code # currently still missing: # Webhook terminology, Telegram notification settings, Strategy/Config settings - - assert "populate_entry_trend" in modified_code1 - assert "populate_exit_trend" in modified_code1 - assert "check_entry_timeout" in modified_code1 - assert "check_exit_timeout" in modified_code1 - assert "custom_exit" in modified_code1 - assert "INTERFACE_VERSION = 3" in modified_code1 - - assert "timeframe" in modified_code2 - # check for not editing hyperopt spaces - assert "space='buy'" in modified_code2 - assert "space='sell'" in modified_code2 - - assert "use_exit_signal" in modified_code3 - assert "exit_profit_only" in modified_code3 - assert "exit_profit_offset" in modified_code3 - assert "ignore_roi_if_entry_signal" in modified_code3 - assert "force_entry_enable" in modified_code3 - - assert "enter_long" in modified_code4 - assert "exit_long" in modified_code4 - assert "enter_tag" in modified_code4 - - assert "exit_reason" in modified_code5 - - assert "'entry': 'gtc'" in modified_code6 - assert "'exit': 'ioc'" in modified_code6 - assert "'entry': 'limit'" in modified_code6 - assert "'exit': 'market'" in modified_code6 - assert "'entry': 1" in modified_code6 - assert "'exit': 2" in modified_code6 - - assert "exit_reason" in modified_code7 - assert "exit_reason == 'stop_loss'" in modified_code7 - - # those tests currently don't work, next in line. - assert "exit_signal" in modified_code8 - assert "exit_reason" in modified_code8 - assert "force_exit" in modified_code8 - assert "emergency_exit" in modified_code8 - - assert "This is the 1st comment" in modified_code9 - assert "This is the 2nd comment" in modified_code9 - assert "This is the 3rd comment" in modified_code9 From f5848ea891723fcdf33e8794f2018c0547f8252d Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 12 Mar 2023 16:29:18 +0100 Subject: [PATCH 130/229] Add test for successful_buys --- tests/test_strategy_updater.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/test_strategy_updater.py b/tests/test_strategy_updater.py index 7205a609d..4aad152bf 100644 --- a/tests/test_strategy_updater.py +++ b/tests/test_strategy_updater.py @@ -84,9 +84,11 @@ def test_strategy_updater_method_params(default_conf, caplog) -> None: instance_strategy_updater = StrategyUpdater() modified_code = instance_strategy_updater.update_code(""" def confirm_trade_exit(sell_reason: str): + nr_orders = trades.nr_of_successful_buys pass """) assert "exit_reason" in modified_code + assert "nr_orders = trades.nr_of_successful_entries" in modified_code def test_strategy_updater_dicts(default_conf, caplog) -> None: From f584edf809c5413f7136ef7c7e1cda5888f5363d Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 12 Mar 2023 16:45:56 +0100 Subject: [PATCH 131/229] Improve tests by simply running a full strategy through everything --- freqtrade/strategy/strategyupdater.py | 4 ++- tests/commands/test_commands.py | 2 +- tests/test_strategy_updater.py | 42 +++++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/freqtrade/strategy/strategyupdater.py b/freqtrade/strategy/strategyupdater.py index 6fe1f326c..bc692b71c 100644 --- a/freqtrade/strategy/strategyupdater.py +++ b/freqtrade/strategy/strategyupdater.py @@ -3,6 +3,8 @@ from pathlib import Path import ast_comments +from freqtrade.constants import Config + class StrategyUpdater: name_mapping = { @@ -42,7 +44,7 @@ class StrategyUpdater: # create a dictionary that maps the old column names to the new ones rename_dict = {'buy': 'enter_long', 'sell': 'exit_long', 'buy_tag': 'enter_tag'} - def start(self, config, strategy_obj: dict) -> None: + def start(self, config: Config, strategy_obj: dict) -> None: """ Run strategy updater It updates a strategy to v3 with the help of the ast-module diff --git a/tests/commands/test_commands.py b/tests/commands/test_commands.py index 179712c6d..318590b32 100644 --- a/tests/commands/test_commands.py +++ b/tests/commands/test_commands.py @@ -1549,7 +1549,7 @@ def test_start_convert_db(mocker, fee, tmpdir, caplog): assert db_target_file.is_file() -def test_start_strategy_updater(mocker, tmpdir): +def test_start_strategy_updater(mocker, tmpdir): sc_mock = mocker.patch('freqtrade.commands.strategy_utils_commands.start_conversion') teststrats = Path(__file__).parent.parent / 'strategy/strats' args = [ diff --git a/tests/test_strategy_updater.py b/tests/test_strategy_updater.py index 4aad152bf..d3bdd27b5 100644 --- a/tests/test_strategy_updater.py +++ b/tests/test_strategy_updater.py @@ -1,16 +1,56 @@ # pragma pylint: disable=missing-docstring, protected-access, invalid-name +import re +import shutil import sys +from pathlib import Path import pytest +from freqtrade.commands.strategy_utils_commands import start_strategy_update from freqtrade.strategy.strategyupdater import StrategyUpdater +from tests.conftest import get_args if sys.version_info < (3, 9): pytest.skip("StrategyUpdater is not compatible with Python 3.8", allow_module_level=True) +def test_strategy_updater_start(tmpdir, capsys) -> None: + # Effective test without mocks. + teststrats = Path(__file__).parent / 'strategy/strats' + tmpdirp = Path(tmpdir) / "strategies" + tmpdirp.mkdir() + shutil.copy(teststrats / 'strategy_test_v2.py', tmpdirp) + old_code = (teststrats / 'strategy_test_v2.py').read_text() + + args = [ + "strategy-updater", + "--userdir", + str(tmpdir), + "--strategy-list", + "StrategyTestV2" + ] + pargs = get_args(args) + pargs['config'] = None + + start_strategy_update(pargs) + + assert Path(tmpdir / "strategies_orig_updater").exists() + # Backup file exists + assert Path(tmpdir / "strategies_orig_updater" / 'strategy_test_v2.py').exists() + # updated file exists + new_file = Path(tmpdirp / 'strategy_test_v2.py') + assert new_file.exists() + new_code = new_file.read_text() + assert 'INTERFACE_VERSION = 3' in new_code + assert 'INTERFACE_VERSION = 2' in old_code + captured = capsys.readouterr() + + assert 'Conversion of strategy_test_v2.py started.' in captured.out + assert re.search(r'Conversion of strategy_test_v2\.py took .* seconds', captured.out) + + def test_strategy_updater_methods(default_conf, caplog) -> None: instance_strategy_updater = StrategyUpdater() @@ -155,6 +195,7 @@ import freqtrade.vendor.qtpylib.indicators as qtpylib class someStrategy(IStrategy): + INTERFACE_VERSION = 2 # This is the 3rd comment # This attribute will be overridden if the config file contains "minimal_roi" minimal_roi = { @@ -168,5 +209,6 @@ class someStrategy(IStrategy): assert "This is the 1st comment" in modified_code assert "This is the 2nd comment" in modified_code assert "This is the 3rd comment" in modified_code + assert "INTERFACE_VERSION = 3" in modified_code # currently still missing: # Webhook terminology, Telegram notification settings, Strategy/Config settings From a10f78e3ef3d2ee3c1605ec8c22dee46d64525cf Mon Sep 17 00:00:00 2001 From: initrv Date: Sun, 12 Mar 2023 23:29:27 +0300 Subject: [PATCH 132/229] fix increment in case of 0 --- freqtrade/freqai/RL/BaseEnvironment.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/freqtrade/freqai/RL/BaseEnvironment.py b/freqtrade/freqai/RL/BaseEnvironment.py index df2a89d81..a9a9a613c 100644 --- a/freqtrade/freqai/RL/BaseEnvironment.py +++ b/freqtrade/freqai/RL/BaseEnvironment.py @@ -157,7 +157,7 @@ class BaseEnvironment(gym.Env): :param value: `metric` value :param category: `metric` category """ - increment = True if not value else False + increment = True if value is None else False value = 1 if increment else value if category not in self.tensorboard_metrics: From fbca8e65874d78e004b9724bab3ca8dd91b5bf0e Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 12 Mar 2023 21:31:08 +0100 Subject: [PATCH 133/229] Allow empty pairlock reasons through api closes #8312 --- freqtrade/rpc/api_server/api_schemas.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/freqtrade/rpc/api_server/api_schemas.py b/freqtrade/rpc/api_server/api_schemas.py index 064a509fd..18621ccbd 100644 --- a/freqtrade/rpc/api_server/api_schemas.py +++ b/freqtrade/rpc/api_server/api_schemas.py @@ -311,7 +311,7 @@ class LockModel(BaseModel): lock_timestamp: int pair: str side: str - reason: str + reason: Optional[str] class Locks(BaseModel): From 52a091e063e5a4d30557aede4ca11a2a9060275e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 13 Mar 2023 03:57:23 +0000 Subject: [PATCH 134/229] Bump pydantic from 1.10.5 to 1.10.6 Bumps [pydantic](https://github.com/pydantic/pydantic) from 1.10.5 to 1.10.6. - [Release notes](https://github.com/pydantic/pydantic/releases) - [Changelog](https://github.com/pydantic/pydantic/blob/v1.10.6/HISTORY.md) - [Commits](https://github.com/pydantic/pydantic/compare/v1.10.5...v1.10.6) --- updated-dependencies: - dependency-name: pydantic dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 5977a6440..15a1df4a0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -35,7 +35,7 @@ sdnotify==0.3.2 # API Server fastapi==0.92.0 -pydantic==1.10.5 +pydantic==1.10.6 uvicorn==0.20.0 pyjwt==2.6.0 aiofiles==23.1.0 From 22ebf04daa202044596da38461704c8ede669402 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 13 Mar 2023 03:57:29 +0000 Subject: [PATCH 135/229] Bump pytest from 7.2.1 to 7.2.2 Bumps [pytest](https://github.com/pytest-dev/pytest) from 7.2.1 to 7.2.2. - [Release notes](https://github.com/pytest-dev/pytest/releases) - [Changelog](https://github.com/pytest-dev/pytest/blob/main/CHANGELOG.rst) - [Commits](https://github.com/pytest-dev/pytest/compare/7.2.1...7.2.2) --- updated-dependencies: - dependency-name: pytest dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index aa6012b1d..814a85894 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -10,7 +10,7 @@ coveralls==3.3.1 ruff==0.0.254 mypy==1.0.1 pre-commit==3.1.1 -pytest==7.2.1 +pytest==7.2.2 pytest-asyncio==0.20.3 pytest-cov==4.0.0 pytest-mock==3.10.0 From 31daf72cc6e5a945d3abf8b36653c59aae56ecef Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 13 Mar 2023 03:57:40 +0000 Subject: [PATCH 136/229] Bump mypy from 1.0.1 to 1.1.1 Bumps [mypy](https://github.com/python/mypy) from 1.0.1 to 1.1.1. - [Release notes](https://github.com/python/mypy/releases) - [Commits](https://github.com/python/mypy/compare/v1.0.1...v1.1.1) --- updated-dependencies: - dependency-name: mypy dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index aa6012b1d..9ca83271a 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -8,7 +8,7 @@ coveralls==3.3.1 ruff==0.0.254 -mypy==1.0.1 +mypy==1.1.1 pre-commit==3.1.1 pytest==7.2.1 pytest-asyncio==0.20.3 From b800f270920fa3f41d9c60870ceff52a59424928 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 13 Mar 2023 03:57:46 +0000 Subject: [PATCH 137/229] Bump mkdocs-material from 9.1.1 to 9.1.2 Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 9.1.1 to 9.1.2. - [Release notes](https://github.com/squidfunk/mkdocs-material/releases) - [Changelog](https://github.com/squidfunk/mkdocs-material/blob/master/CHANGELOG) - [Commits](https://github.com/squidfunk/mkdocs-material/compare/9.1.1...9.1.2) --- updated-dependencies: - dependency-name: mkdocs-material dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- docs/requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/requirements-docs.txt b/docs/requirements-docs.txt index 1b9a1f9b7..d384a7ec5 100644 --- a/docs/requirements-docs.txt +++ b/docs/requirements-docs.txt @@ -1,6 +1,6 @@ markdown==3.3.7 mkdocs==1.4.2 -mkdocs-material==9.1.1 +mkdocs-material==9.1.2 mdx_truly_sane_lists==1.3 pymdown-extensions==9.10 jinja2==3.1.2 From 82707be7d05077b61a6da6842a351fdf0045ebb2 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 13 Mar 2023 03:57:48 +0000 Subject: [PATCH 138/229] Bump pypa/gh-action-pypi-publish from 1.6.4 to 1.7.1 Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.6.4 to 1.7.1. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.6.4...v1.7.1) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 191a10d1c..7e0483c3d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -425,7 +425,7 @@ jobs: python setup.py sdist bdist_wheel - name: Publish to PyPI (Test) - uses: pypa/gh-action-pypi-publish@v1.6.4 + uses: pypa/gh-action-pypi-publish@v1.7.1 if: (github.event_name == 'release') with: user: __token__ @@ -433,7 +433,7 @@ jobs: repository_url: https://test.pypi.org/legacy/ - name: Publish to PyPI - uses: pypa/gh-action-pypi-publish@v1.6.4 + uses: pypa/gh-action-pypi-publish@v1.7.1 if: (github.event_name == 'release') with: user: __token__ From dc6af9a1a7f4c849628861e4b14ff21947c6c355 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 13 Mar 2023 03:57:54 +0000 Subject: [PATCH 139/229] Bump urllib3 from 1.26.14 to 1.26.15 Bumps [urllib3](https://github.com/urllib3/urllib3) from 1.26.14 to 1.26.15. - [Release notes](https://github.com/urllib3/urllib3/releases) - [Changelog](https://github.com/urllib3/urllib3/blob/main/CHANGES.rst) - [Commits](https://github.com/urllib3/urllib3/compare/1.26.14...1.26.15) --- updated-dependencies: - dependency-name: urllib3 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 5977a6440..f2f7c4cf7 100644 --- a/requirements.txt +++ b/requirements.txt @@ -10,7 +10,7 @@ python-telegram-bot==13.15 arrow==1.2.3 cachetools==4.2.2 requests==2.28.2 -urllib3==1.26.14 +urllib3==1.26.15 jsonschema==4.17.3 TA-Lib==0.4.25 technical==1.4.0 From 10c5adfa5076cbc9b763342a899ae5e67e661bf0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 13 Mar 2023 05:37:55 +0000 Subject: [PATCH 140/229] Bump fastapi from 0.92.0 to 0.94.0 Bumps [fastapi](https://github.com/tiangolo/fastapi) from 0.92.0 to 0.94.0. - [Release notes](https://github.com/tiangolo/fastapi/releases) - [Commits](https://github.com/tiangolo/fastapi/compare/0.92.0...0.94.0) --- updated-dependencies: - dependency-name: fastapi dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 15a1df4a0..53991d9f1 100644 --- a/requirements.txt +++ b/requirements.txt @@ -34,7 +34,7 @@ orjson==3.8.7 sdnotify==0.3.2 # API Server -fastapi==0.92.0 +fastapi==0.94.0 pydantic==1.10.6 uvicorn==0.20.0 pyjwt==2.6.0 From 0e663a5bf80ed3149e0fb7e60984d2869369583d Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 13 Mar 2023 07:06:16 +0100 Subject: [PATCH 141/229] Refresh binance cached leverage tiers --- .../exchange/binance_leverage_tiers.json | 3984 ++++++++++++----- 1 file changed, 2859 insertions(+), 1125 deletions(-) diff --git a/freqtrade/exchange/binance_leverage_tiers.json b/freqtrade/exchange/binance_leverage_tiers.json index 22db74f06..07fdcb5a4 100644 --- a/freqtrade/exchange/binance_leverage_tiers.json +++ b/freqtrade/exchange/binance_leverage_tiers.json @@ -104,10 +104,10 @@ "minNotional": 0.0, "maxNotional": 5000.0, "maintenanceMarginRate": 0.01, - "maxLeverage": 20.0, + "maxLeverage": 25.0, "info": { "bracket": "1", - "initialLeverage": "20", + "initialLeverage": "25", "notionalCap": "5000", "notionalFloor": "0", "maintMarginRatio": "0.01", @@ -120,10 +120,10 @@ "minNotional": 5000.0, "maxNotional": 25000.0, "maintenanceMarginRate": 0.025, - "maxLeverage": 10.0, + "maxLeverage": 20.0, "info": { "bracket": "2", - "initialLeverage": "10", + "initialLeverage": "20", "notionalCap": "25000", "notionalFloor": "5000", "maintMarginRatio": "0.025", @@ -134,13 +134,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, + "maxNotional": 400000.0, "maintenanceMarginRate": 0.05, - "maxLeverage": 8.0, + "maxLeverage": 10.0, "info": { "bracket": "3", - "initialLeverage": "8", - "notionalCap": "100000", + "initialLeverage": "10", + "notionalCap": "400000", "notionalFloor": "25000", "maintMarginRatio": "0.05", "cum": "700.0" @@ -149,49 +149,65 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, + "minNotional": 400000.0, + "maxNotional": 1000000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "4", "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", + "notionalCap": "1000000", + "notionalFloor": "400000", "maintMarginRatio": "0.1", - "cum": "5700.0" + "cum": "20700.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, - "maxNotional": 1000000.0, + "minNotional": 1000000.0, + "maxNotional": 2000000.0, "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maxLeverage": 4.0, "info": { "bracket": "5", - "initialLeverage": "2", - "notionalCap": "1000000", - "notionalFloor": "250000", + "initialLeverage": "4", + "notionalCap": "2000000", + "notionalFloor": "1000000", "maintMarginRatio": "0.125", - "cum": "11950.0" + "cum": "45700.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 1000000.0, - "maxNotional": 5000000.0, + "minNotional": 2000000.0, + "maxNotional": 6000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "6000000", + "notionalFloor": "2000000", + "maintMarginRatio": "0.25", + "cum": "295700.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 6000000.0, + "maxNotional": 10000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "7", "initialLeverage": "1", - "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalCap": "10000000", + "notionalFloor": "6000000", "maintMarginRatio": "0.5", - "cum": "386950.0" + "cum": "1795700.0" } } ], @@ -658,10 +674,10 @@ "minNotional": 0.0, "maxNotional": 5000.0, "maintenanceMarginRate": 0.01, - "maxLeverage": 20.0, + "maxLeverage": 25.0, "info": { "bracket": "1", - "initialLeverage": "20", + "initialLeverage": "25", "notionalCap": "5000", "notionalFloor": "0", "maintMarginRatio": "0.01", @@ -674,10 +690,10 @@ "minNotional": 5000.0, "maxNotional": 25000.0, "maintenanceMarginRate": 0.025, - "maxLeverage": 10.0, + "maxLeverage": 20.0, "info": { "bracket": "2", - "initialLeverage": "10", + "initialLeverage": "20", "notionalCap": "25000", "notionalFloor": "5000", "maintMarginRatio": "0.025", @@ -688,18 +704,132 @@ "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, + "maxNotional": 400000.0, "maintenanceMarginRate": 0.05, - "maxLeverage": 8.0, + "maxLeverage": 10.0, "info": { "bracket": "3", - "initialLeverage": "8", - "notionalCap": "100000", + "initialLeverage": "10", + "notionalCap": "400000", "notionalFloor": "25000", "maintMarginRatio": "0.05", "cum": "700.0" } }, + { + "tier": 4.0, + "currency": "USDT", + "minNotional": 400000.0, + "maxNotional": 1000000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "4", + "initialLeverage": "5", + "notionalCap": "1000000", + "notionalFloor": "400000", + "maintMarginRatio": "0.1", + "cum": "20700.0" + } + }, + { + "tier": 5.0, + "currency": "USDT", + "minNotional": 1000000.0, + "maxNotional": 2000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 4.0, + "info": { + "bracket": "5", + "initialLeverage": "4", + "notionalCap": "2000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.125", + "cum": "45700.0" + } + }, + { + "tier": 6.0, + "currency": "USDT", + "minNotional": 2000000.0, + "maxNotional": 6000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "6000000", + "notionalFloor": "2000000", + "maintMarginRatio": "0.25", + "cum": "295700.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 6000000.0, + "maxNotional": 10000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "7", + "initialLeverage": "1", + "notionalCap": "10000000", + "notionalFloor": "6000000", + "maintMarginRatio": "0.5", + "cum": "1795700.0" + } + } + ], + "ACH/USDT:USDT": [ + { + "tier": 1.0, + "currency": "USDT", + "minNotional": 0.0, + "maxNotional": 5000.0, + "maintenanceMarginRate": 0.02, + "maxLeverage": 20.0, + "info": { + "bracket": "1", + "initialLeverage": "20", + "notionalCap": "5000", + "notionalFloor": "0", + "maintMarginRatio": "0.02", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "USDT", + "minNotional": 5000.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 15.0, + "info": { + "bracket": "2", + "initialLeverage": "15", + "notionalCap": "25000", + "notionalFloor": "5000", + "maintMarginRatio": "0.025", + "cum": "25.0" + } + }, + { + "tier": 3.0, + "currency": "USDT", + "minNotional": 25000.0, + "maxNotional": 100000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "3", + "initialLeverage": "10", + "notionalCap": "100000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "650.0" + } + }, { "tier": 4.0, "currency": "USDT", @@ -713,7 +843,7 @@ "notionalCap": "250000", "notionalFloor": "100000", "maintMarginRatio": "0.1", - "cum": "5700.0" + "cum": "5650.0" } }, { @@ -729,7 +859,7 @@ "notionalCap": "1000000", "notionalFloor": "250000", "maintMarginRatio": "0.125", - "cum": "11950.0" + "cum": "11900.0" } }, { @@ -745,7 +875,7 @@ "notionalCap": "5000000", "notionalFloor": "1000000", "maintMarginRatio": "0.5", - "cum": "386950.0" + "cum": "386900.0" } } ], @@ -1114,10 +1244,10 @@ "minNotional": 0.0, "maxNotional": 5000.0, "maintenanceMarginRate": 0.02, - "maxLeverage": 20.0, + "maxLeverage": 25.0, "info": { "bracket": "1", - "initialLeverage": "20", + "initialLeverage": "25", "notionalCap": "5000", "notionalFloor": "0", "maintMarginRatio": "0.02", @@ -1130,10 +1260,10 @@ "minNotional": 5000.0, "maxNotional": 25000.0, "maintenanceMarginRate": 0.025, - "maxLeverage": 15.0, + "maxLeverage": 20.0, "info": { "bracket": "2", - "initialLeverage": "15", + "initialLeverage": "20", "notionalCap": "25000", "notionalFloor": "5000", "maintMarginRatio": "0.025", @@ -1144,13 +1274,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, + "maxNotional": 200000.0, "maintenanceMarginRate": 0.05, "maxLeverage": 10.0, "info": { "bracket": "3", "initialLeverage": "10", - "notionalCap": "100000", + "notionalCap": "200000", "notionalFloor": "25000", "maintMarginRatio": "0.05", "cum": "650.0" @@ -1159,49 +1289,65 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, + "minNotional": 200000.0, + "maxNotional": 500000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "4", "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", + "notionalCap": "500000", + "notionalFloor": "200000", "maintMarginRatio": "0.1", - "cum": "5650.0" + "cum": "10650.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, + "minNotional": 500000.0, "maxNotional": 1000000.0, "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maxLeverage": 4.0, "info": { "bracket": "5", - "initialLeverage": "2", + "initialLeverage": "4", "notionalCap": "1000000", - "notionalFloor": "250000", + "notionalFloor": "500000", "maintMarginRatio": "0.125", - "cum": "11900.0" + "cum": "23150.0" } }, { "tier": 6.0, "currency": "USDT", "minNotional": 1000000.0, + "maxNotional": 3000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "3000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.25", + "cum": "148150.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 3000000.0, "maxNotional": 5000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "7", "initialLeverage": "1", "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalFloor": "3000000", "maintMarginRatio": "0.5", - "cum": "386900.0" + "cum": "898150.0" } } ], @@ -1701,14 +1847,14 @@ "currency": "USDT", "minNotional": 0.0, "maxNotional": 5000.0, - "maintenanceMarginRate": 0.012, - "maxLeverage": 20.0, + "maintenanceMarginRate": 0.01, + "maxLeverage": 25.0, "info": { "bracket": "1", - "initialLeverage": "20", + "initialLeverage": "25", "notionalCap": "5000", "notionalFloor": "0", - "maintMarginRatio": "0.012", + "maintMarginRatio": "0.01", "cum": "0.0" } }, @@ -1718,78 +1864,94 @@ "minNotional": 5000.0, "maxNotional": 25000.0, "maintenanceMarginRate": 0.025, - "maxLeverage": 10.0, + "maxLeverage": 20.0, "info": { "bracket": "2", - "initialLeverage": "10", + "initialLeverage": "20", "notionalCap": "25000", "notionalFloor": "5000", "maintMarginRatio": "0.025", - "cum": "65.0" + "cum": "75.0" } }, { "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, + "maxNotional": 400000.0, "maintenanceMarginRate": 0.05, - "maxLeverage": 8.0, + "maxLeverage": 10.0, "info": { "bracket": "3", - "initialLeverage": "8", - "notionalCap": "100000", + "initialLeverage": "10", + "notionalCap": "400000", "notionalFloor": "25000", "maintMarginRatio": "0.05", - "cum": "690.0" + "cum": "700.0" } }, { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, + "minNotional": 400000.0, + "maxNotional": 1000000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "4", "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", + "notionalCap": "1000000", + "notionalFloor": "400000", "maintMarginRatio": "0.1", - "cum": "5690.0" + "cum": "20700.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, - "maxNotional": 1000000.0, + "minNotional": 1000000.0, + "maxNotional": 2000000.0, "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maxLeverage": 4.0, "info": { "bracket": "5", - "initialLeverage": "2", - "notionalCap": "1000000", - "notionalFloor": "250000", + "initialLeverage": "4", + "notionalCap": "2000000", + "notionalFloor": "1000000", "maintMarginRatio": "0.125", - "cum": "11940.0" + "cum": "45700.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 1000000.0, - "maxNotional": 5000000.0, + "minNotional": 2000000.0, + "maxNotional": 6000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "6000000", + "notionalFloor": "2000000", + "maintMarginRatio": "0.25", + "cum": "295700.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 6000000.0, + "maxNotional": 10000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "7", "initialLeverage": "1", - "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalCap": "10000000", + "notionalFloor": "6000000", "maintMarginRatio": "0.5", - "cum": "386940.0" + "cum": "1795700.0" } } ], @@ -2353,14 +2515,14 @@ "currency": "USDT", "minNotional": 0.0, "maxNotional": 5000.0, - "maintenanceMarginRate": 0.015, - "maxLeverage": 25.0, + "maintenanceMarginRate": 0.01, + "maxLeverage": 50.0, "info": { "bracket": "1", - "initialLeverage": "25", + "initialLeverage": "50", "notionalCap": "5000", "notionalFloor": "0", - "maintMarginRatio": "0.015", + "maintMarginRatio": "0.01", "cum": "0.0" } }, @@ -2369,14 +2531,14 @@ "currency": "USDT", "minNotional": 5000.0, "maxNotional": 25000.0, - "maintenanceMarginRate": 0.02, - "maxLeverage": 20.0, + "maintenanceMarginRate": 0.015, + "maxLeverage": 25.0, "info": { "bracket": "2", - "initialLeverage": "20", + "initialLeverage": "25", "notionalCap": "25000", "notionalFloor": "5000", - "maintMarginRatio": "0.02", + "maintMarginRatio": "0.015", "cum": "25.0" } }, @@ -2384,112 +2546,96 @@ "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 150000.0, - "maintenanceMarginRate": 0.0225, - "maxLeverage": 15.0, + "maxNotional": 300000.0, + "maintenanceMarginRate": 0.02, + "maxLeverage": 20.0, "info": { "bracket": "3", - "initialLeverage": "15", - "notionalCap": "150000", + "initialLeverage": "20", + "notionalCap": "300000", "notionalFloor": "25000", - "maintMarginRatio": "0.0225", - "cum": "87.5" + "maintMarginRatio": "0.02", + "cum": "150.0" } }, { "tier": 4.0, "currency": "USDT", - "minNotional": 150000.0, - "maxNotional": 250000.0, - "maintenanceMarginRate": 0.025, + "minNotional": 300000.0, + "maxNotional": 1200000.0, + "maintenanceMarginRate": 0.05, "maxLeverage": 10.0, "info": { "bracket": "4", "initialLeverage": "10", - "notionalCap": "250000", - "notionalFloor": "150000", - "maintMarginRatio": "0.025", - "cum": "462.5" + "notionalCap": "1200000", + "notionalFloor": "300000", + "maintMarginRatio": "0.05", + "cum": "9150.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, - "maxNotional": 1000000.0, - "maintenanceMarginRate": 0.05, - "maxLeverage": 8.0, + "minNotional": 1200000.0, + "maxNotional": 3000000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, "info": { "bracket": "5", - "initialLeverage": "8", - "notionalCap": "1000000", - "notionalFloor": "250000", - "maintMarginRatio": "0.05", - "cum": "6712.5" + "initialLeverage": "5", + "notionalCap": "3000000", + "notionalFloor": "1200000", + "maintMarginRatio": "0.1", + "cum": "69150.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 1000000.0, - "maxNotional": 2000000.0, - "maintenanceMarginRate": 0.1, - "maxLeverage": 5.0, + "minNotional": 3000000.0, + "maxNotional": 6000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 4.0, "info": { "bracket": "6", - "initialLeverage": "5", - "notionalCap": "2000000", - "notionalFloor": "1000000", - "maintMarginRatio": "0.1", - "cum": "56712.5" + "initialLeverage": "4", + "notionalCap": "6000000", + "notionalFloor": "3000000", + "maintMarginRatio": "0.125", + "cum": "144150.0" } }, { "tier": 7.0, "currency": "USDT", - "minNotional": 2000000.0, - "maxNotional": 5000000.0, - "maintenanceMarginRate": 0.125, - "maxLeverage": 4.0, + "minNotional": 6000000.0, + "maxNotional": 18000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, "info": { "bracket": "7", - "initialLeverage": "4", - "notionalCap": "5000000", - "notionalFloor": "2000000", - "maintMarginRatio": "0.125", - "cum": "106712.5" + "initialLeverage": "2", + "notionalCap": "18000000", + "notionalFloor": "6000000", + "maintMarginRatio": "0.25", + "cum": "894150.0" } }, { "tier": 8.0, "currency": "USDT", - "minNotional": 5000000.0, - "maxNotional": 10000000.0, - "maintenanceMarginRate": 0.25, - "maxLeverage": 2.0, - "info": { - "bracket": "8", - "initialLeverage": "2", - "notionalCap": "10000000", - "notionalFloor": "5000000", - "maintMarginRatio": "0.25", - "cum": "731712.5" - } - }, - { - "tier": 9.0, - "currency": "USDT", - "minNotional": 10000000.0, - "maxNotional": 20000000.0, + "minNotional": 18000000.0, + "maxNotional": 30000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "9", + "bracket": "8", "initialLeverage": "1", - "notionalCap": "20000000", - "notionalFloor": "10000000", + "notionalCap": "30000000", + "notionalFloor": "18000000", "maintMarginRatio": "0.5", - "cum": "3231712.5" + "cum": "5394150.0" } } ], @@ -2891,14 +3037,14 @@ "currency": "USDT", "minNotional": 0.0, "maxNotional": 5000.0, - "maintenanceMarginRate": 0.0065, + "maintenanceMarginRate": 0.006, "maxLeverage": 50.0, "info": { "bracket": "1", "initialLeverage": "50", "notionalCap": "5000", "notionalFloor": "0", - "maintMarginRatio": "0.0065", + "maintMarginRatio": "0.006", "cum": "0.0" } }, @@ -2915,61 +3061,61 @@ "notionalCap": "50000", "notionalFloor": "5000", "maintMarginRatio": "0.01", - "cum": "17.5" + "cum": "20.0" } }, { "tier": 3.0, "currency": "USDT", "minNotional": 50000.0, - "maxNotional": 200000.0, + "maxNotional": 600000.0, "maintenanceMarginRate": 0.025, "maxLeverage": 20.0, "info": { "bracket": "3", "initialLeverage": "20", - "notionalCap": "200000", + "notionalCap": "600000", "notionalFloor": "50000", "maintMarginRatio": "0.025", - "cum": "767.5" + "cum": "770.0" } }, { "tier": 4.0, "currency": "USDT", - "minNotional": 200000.0, - "maxNotional": 400000.0, + "minNotional": 600000.0, + "maxNotional": 1200000.0, "maintenanceMarginRate": 0.05, "maxLeverage": 10.0, "info": { "bracket": "4", "initialLeverage": "10", - "notionalCap": "400000", - "notionalFloor": "200000", + "notionalCap": "1200000", + "notionalFloor": "600000", "maintMarginRatio": "0.05", - "cum": "5767.5" + "cum": "15770.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 400000.0, - "maxNotional": 1000000.0, + "minNotional": 1200000.0, + "maxNotional": 3200000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "5", "initialLeverage": "5", - "notionalCap": "1000000", - "notionalFloor": "400000", + "notionalCap": "3200000", + "notionalFloor": "1200000", "maintMarginRatio": "0.1", - "cum": "25767.5" + "cum": "75770.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 1000000.0, + "minNotional": 3200000.0, "maxNotional": 5000000.0, "maintenanceMarginRate": 0.125, "maxLeverage": 4.0, @@ -2977,41 +3123,41 @@ "bracket": "6", "initialLeverage": "4", "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalFloor": "3200000", "maintMarginRatio": "0.125", - "cum": "50767.5" + "cum": "155770.0" } }, { "tier": 7.0, "currency": "USDT", "minNotional": 5000000.0, - "maxNotional": 6000000.0, + "maxNotional": 12000000.0, "maintenanceMarginRate": 0.25, "maxLeverage": 2.0, "info": { "bracket": "7", "initialLeverage": "2", - "notionalCap": "6000000", + "notionalCap": "12000000", "notionalFloor": "5000000", "maintMarginRatio": "0.25", - "cum": "675767.5" + "cum": "780770.0" } }, { "tier": 8.0, "currency": "USDT", - "minNotional": 6000000.0, - "maxNotional": 10000000.0, + "minNotional": 12000000.0, + "maxNotional": 20000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { "bracket": "8", "initialLeverage": "1", - "notionalCap": "10000000", - "notionalFloor": "6000000", + "notionalCap": "20000000", + "notionalFloor": "12000000", "maintMarginRatio": "0.5", - "cum": "2175767.5" + "cum": "3780770.0" } } ], @@ -4762,96 +4908,96 @@ "tier": 1.0, "currency": "USDT", "minNotional": 0.0, - "maxNotional": 25000.0, - "maintenanceMarginRate": 0.025, - "maxLeverage": 8.0, + "maxNotional": 5000.0, + "maintenanceMarginRate": 0.02, + "maxLeverage": 20.0, "info": { "bracket": "1", - "initialLeverage": "8", - "notionalCap": "25000", + "initialLeverage": "20", + "notionalCap": "5000", "notionalFloor": "0", - "maintMarginRatio": "0.025", + "maintMarginRatio": "0.02", "cum": "0.0" } }, { "tier": 2.0, "currency": "USDT", - "minNotional": 25000.0, - "maxNotional": 250000.0, - "maintenanceMarginRate": 0.05, - "maxLeverage": 6.0, + "minNotional": 5000.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 15.0, "info": { "bracket": "2", - "initialLeverage": "6", - "notionalCap": "250000", - "notionalFloor": "25000", - "maintMarginRatio": "0.05", - "cum": "625.0" + "initialLeverage": "15", + "notionalCap": "25000", + "notionalFloor": "5000", + "maintMarginRatio": "0.025", + "cum": "25.0" } }, { "tier": 3.0, "currency": "USDT", - "minNotional": 250000.0, - "maxNotional": 500000.0, - "maintenanceMarginRate": 0.1, - "maxLeverage": 5.0, + "minNotional": 25000.0, + "maxNotional": 100000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, "info": { "bracket": "3", - "initialLeverage": "5", - "notionalCap": "500000", - "notionalFloor": "250000", - "maintMarginRatio": "0.1", - "cum": "13125.0" + "initialLeverage": "10", + "notionalCap": "100000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "650.0" } }, { "tier": 4.0, "currency": "USDT", - "minNotional": 500000.0, - "maxNotional": 1000000.0, - "maintenanceMarginRate": 0.125, - "maxLeverage": 4.0, + "minNotional": 100000.0, + "maxNotional": 250000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, "info": { "bracket": "4", - "initialLeverage": "4", - "notionalCap": "1000000", - "notionalFloor": "500000", - "maintMarginRatio": "0.125", - "cum": "25625.0" + "initialLeverage": "5", + "notionalCap": "250000", + "notionalFloor": "100000", + "maintMarginRatio": "0.1", + "cum": "5650.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 1000000.0, - "maxNotional": 1500000.0, - "maintenanceMarginRate": 0.25, + "minNotional": 250000.0, + "maxNotional": 1000000.0, + "maintenanceMarginRate": 0.125, "maxLeverage": 2.0, "info": { "bracket": "5", "initialLeverage": "2", - "notionalCap": "1500000", - "notionalFloor": "1000000", - "maintMarginRatio": "0.25", - "cum": "150625.0" + "notionalCap": "1000000", + "notionalFloor": "250000", + "maintMarginRatio": "0.125", + "cum": "11900.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 1500000.0, - "maxNotional": 2000000.0, + "minNotional": 1000000.0, + "maxNotional": 5000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { "bracket": "6", "initialLeverage": "1", - "notionalCap": "2000000", - "notionalFloor": "1500000", + "notionalCap": "5000000", + "notionalFloor": "1000000", "maintMarginRatio": "0.5", - "cum": "525625.0" + "cum": "386900.0" } } ], @@ -5054,13 +5200,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 250000.0, - "maxNotional": 1000000.0, + "maxNotional": 3000000.0, "maintenanceMarginRate": 0.01, "maxLeverage": 50.0, "info": { "bracket": "3", "initialLeverage": "50", - "notionalCap": "1000000", + "notionalCap": "3000000", "notionalFloor": "250000", "maintMarginRatio": "0.01", "cum": "1300.0" @@ -5069,55 +5215,55 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 1000000.0, - "maxNotional": 10000000.0, + "minNotional": 3000000.0, + "maxNotional": 15000000.0, "maintenanceMarginRate": 0.025, "maxLeverage": 20.0, "info": { "bracket": "4", "initialLeverage": "20", - "notionalCap": "10000000", - "notionalFloor": "1000000", + "notionalCap": "15000000", + "notionalFloor": "3000000", "maintMarginRatio": "0.025", - "cum": "16300.0" + "cum": "46300.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 10000000.0, - "maxNotional": 20000000.0, + "minNotional": 15000000.0, + "maxNotional": 30000000.0, "maintenanceMarginRate": 0.05, "maxLeverage": 10.0, "info": { "bracket": "5", "initialLeverage": "10", - "notionalCap": "20000000", - "notionalFloor": "10000000", + "notionalCap": "30000000", + "notionalFloor": "15000000", "maintMarginRatio": "0.05", - "cum": "266300.0" + "cum": "421300.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 20000000.0, - "maxNotional": 50000000.0, + "minNotional": 30000000.0, + "maxNotional": 80000000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "6", "initialLeverage": "5", - "notionalCap": "50000000", - "notionalFloor": "20000000", + "notionalCap": "80000000", + "notionalFloor": "30000000", "maintMarginRatio": "0.1", - "cum": "1266300.0" + "cum": "1921300.0" } }, { "tier": 7.0, "currency": "USDT", - "minNotional": 50000000.0, + "minNotional": 80000000.0, "maxNotional": 100000000.0, "maintenanceMarginRate": 0.125, "maxLeverage": 4.0, @@ -5125,9 +5271,9 @@ "bracket": "7", "initialLeverage": "4", "notionalCap": "100000000", - "notionalFloor": "50000000", + "notionalFloor": "80000000", "maintMarginRatio": "0.125", - "cum": "2516300.0" + "cum": "3921300.0" } }, { @@ -5143,7 +5289,7 @@ "notionalCap": "200000000", "notionalFloor": "100000000", "maintMarginRatio": "0.15", - "cum": "5016300.0" + "cum": "6421300.0" } }, { @@ -5159,7 +5305,7 @@ "notionalCap": "300000000", "notionalFloor": "200000000", "maintMarginRatio": "0.25", - "cum": "2.50163E7" + "cum": "2.64213E7" } }, { @@ -5175,7 +5321,7 @@ "notionalCap": "500000000", "notionalFloor": "300000000", "maintMarginRatio": "0.5", - "cum": "1.000163E8" + "cum": "1.014213E8" } } ], @@ -5881,6 +6027,136 @@ } } ], + "CFX/USDT:USDT": [ + { + "tier": 1.0, + "currency": "USDT", + "minNotional": 0.0, + "maxNotional": 5000.0, + "maintenanceMarginRate": 0.01, + "maxLeverage": 50.0, + "info": { + "bracket": "1", + "initialLeverage": "50", + "notionalCap": "5000", + "notionalFloor": "0", + "maintMarginRatio": "0.01", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "USDT", + "minNotional": 5000.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.015, + "maxLeverage": 25.0, + "info": { + "bracket": "2", + "initialLeverage": "25", + "notionalCap": "25000", + "notionalFloor": "5000", + "maintMarginRatio": "0.015", + "cum": "25.0" + } + }, + { + "tier": 3.0, + "currency": "USDT", + "minNotional": 25000.0, + "maxNotional": 300000.0, + "maintenanceMarginRate": 0.02, + "maxLeverage": 20.0, + "info": { + "bracket": "3", + "initialLeverage": "20", + "notionalCap": "300000", + "notionalFloor": "25000", + "maintMarginRatio": "0.02", + "cum": "150.0" + } + }, + { + "tier": 4.0, + "currency": "USDT", + "minNotional": 300000.0, + "maxNotional": 1200000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "4", + "initialLeverage": "10", + "notionalCap": "1200000", + "notionalFloor": "300000", + "maintMarginRatio": "0.05", + "cum": "9150.0" + } + }, + { + "tier": 5.0, + "currency": "USDT", + "minNotional": 1200000.0, + "maxNotional": 3000000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "5", + "initialLeverage": "5", + "notionalCap": "3000000", + "notionalFloor": "1200000", + "maintMarginRatio": "0.1", + "cum": "69150.0" + } + }, + { + "tier": 6.0, + "currency": "USDT", + "minNotional": 3000000.0, + "maxNotional": 6000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 4.0, + "info": { + "bracket": "6", + "initialLeverage": "4", + "notionalCap": "6000000", + "notionalFloor": "3000000", + "maintMarginRatio": "0.125", + "cum": "144150.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 6000000.0, + "maxNotional": 18000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "7", + "initialLeverage": "2", + "notionalCap": "18000000", + "notionalFloor": "6000000", + "maintMarginRatio": "0.25", + "cum": "894150.0" + } + }, + { + "tier": 8.0, + "currency": "USDT", + "minNotional": 18000000.0, + "maxNotional": 30000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "8", + "initialLeverage": "1", + "notionalCap": "30000000", + "notionalFloor": "18000000", + "maintMarginRatio": "0.5", + "cum": "5394150.0" + } + } + ], "CHR/USDT:USDT": [ { "tier": 1.0, @@ -6077,6 +6353,218 @@ } } ], + "CKB/USDT:USDT": [ + { + "tier": 1.0, + "currency": "USDT", + "minNotional": 0.0, + "maxNotional": 5000.0, + "maintenanceMarginRate": 0.02, + "maxLeverage": 20.0, + "info": { + "bracket": "1", + "initialLeverage": "20", + "notionalCap": "5000", + "notionalFloor": "0", + "maintMarginRatio": "0.02", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "USDT", + "minNotional": 5000.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 15.0, + "info": { + "bracket": "2", + "initialLeverage": "15", + "notionalCap": "25000", + "notionalFloor": "5000", + "maintMarginRatio": "0.025", + "cum": "25.0" + } + }, + { + "tier": 3.0, + "currency": "USDT", + "minNotional": 25000.0, + "maxNotional": 200000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "3", + "initialLeverage": "10", + "notionalCap": "200000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "650.0" + } + }, + { + "tier": 4.0, + "currency": "USDT", + "minNotional": 200000.0, + "maxNotional": 500000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "4", + "initialLeverage": "5", + "notionalCap": "500000", + "notionalFloor": "200000", + "maintMarginRatio": "0.1", + "cum": "10650.0" + } + }, + { + "tier": 5.0, + "currency": "USDT", + "minNotional": 500000.0, + "maxNotional": 1000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 4.0, + "info": { + "bracket": "5", + "initialLeverage": "4", + "notionalCap": "1000000", + "notionalFloor": "500000", + "maintMarginRatio": "0.125", + "cum": "23150.0" + } + }, + { + "tier": 6.0, + "currency": "USDT", + "minNotional": 1000000.0, + "maxNotional": 3000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "3000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.25", + "cum": "148150.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 3000000.0, + "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "7", + "initialLeverage": "1", + "notionalCap": "5000000", + "notionalFloor": "3000000", + "maintMarginRatio": "0.5", + "cum": "898150.0" + } + } + ], + "COCOS/USDT:USDT": [ + { + "tier": 1.0, + "currency": "USDT", + "minNotional": 0.0, + "maxNotional": 5000.0, + "maintenanceMarginRate": 0.02, + "maxLeverage": 20.0, + "info": { + "bracket": "1", + "initialLeverage": "20", + "notionalCap": "5000", + "notionalFloor": "0", + "maintMarginRatio": "0.02", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "USDT", + "minNotional": 5000.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 15.0, + "info": { + "bracket": "2", + "initialLeverage": "15", + "notionalCap": "25000", + "notionalFloor": "5000", + "maintMarginRatio": "0.025", + "cum": "25.0" + } + }, + { + "tier": 3.0, + "currency": "USDT", + "minNotional": 25000.0, + "maxNotional": 100000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "3", + "initialLeverage": "10", + "notionalCap": "100000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "650.0" + } + }, + { + "tier": 4.0, + "currency": "USDT", + "minNotional": 100000.0, + "maxNotional": 250000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "4", + "initialLeverage": "5", + "notionalCap": "250000", + "notionalFloor": "100000", + "maintMarginRatio": "0.1", + "cum": "5650.0" + } + }, + { + "tier": 5.0, + "currency": "USDT", + "minNotional": 250000.0, + "maxNotional": 1000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 2.0, + "info": { + "bracket": "5", + "initialLeverage": "2", + "notionalCap": "1000000", + "notionalFloor": "250000", + "maintMarginRatio": "0.125", + "cum": "11900.0" + } + }, + { + "tier": 6.0, + "currency": "USDT", + "minNotional": 1000000.0, + "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "6", + "initialLeverage": "1", + "notionalCap": "5000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.5", + "cum": "386900.0" + } + } + ], "COMP/USDT:USDT": [ { "tier": 1.0, @@ -7944,10 +8432,10 @@ "minNotional": 0.0, "maxNotional": 5000.0, "maintenanceMarginRate": 0.02, - "maxLeverage": 20.0, + "maxLeverage": 25.0, "info": { "bracket": "1", - "initialLeverage": "20", + "initialLeverage": "25", "notionalCap": "5000", "notionalFloor": "0", "maintMarginRatio": "0.02", @@ -7960,10 +8448,10 @@ "minNotional": 5000.0, "maxNotional": 25000.0, "maintenanceMarginRate": 0.025, - "maxLeverage": 10.0, + "maxLeverage": 20.0, "info": { "bracket": "2", - "initialLeverage": "10", + "initialLeverage": "20", "notionalCap": "25000", "notionalFloor": "5000", "maintMarginRatio": "0.025", @@ -7974,13 +8462,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, + "maxNotional": 200000.0, "maintenanceMarginRate": 0.05, - "maxLeverage": 8.0, + "maxLeverage": 10.0, "info": { "bracket": "3", - "initialLeverage": "8", - "notionalCap": "100000", + "initialLeverage": "10", + "notionalCap": "200000", "notionalFloor": "25000", "maintMarginRatio": "0.05", "cum": "650.0" @@ -7989,105 +8477,7 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, - "maintenanceMarginRate": 0.1, - "maxLeverage": 5.0, - "info": { - "bracket": "4", - "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", - "maintMarginRatio": "0.1", - "cum": "5650.0" - } - }, - { - "tier": 5.0, - "currency": "USDT", - "minNotional": 250000.0, - "maxNotional": 1000000.0, - "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, - "info": { - "bracket": "5", - "initialLeverage": "2", - "notionalCap": "1000000", - "notionalFloor": "250000", - "maintMarginRatio": "0.125", - "cum": "11900.0" - } - }, - { - "tier": 6.0, - "currency": "USDT", - "minNotional": 1000000.0, - "maxNotional": 3000000.0, - "maintenanceMarginRate": 0.5, - "maxLeverage": 1.0, - "info": { - "bracket": "6", - "initialLeverage": "1", - "notionalCap": "3000000", - "notionalFloor": "1000000", - "maintMarginRatio": "0.5", - "cum": "386900.0" - } - } - ], - "DYDX/USDT:USDT": [ - { - "tier": 1.0, - "currency": "USDT", - "minNotional": 0.0, - "maxNotional": 50000.0, - "maintenanceMarginRate": 0.02, - "maxLeverage": 20.0, - "info": { - "bracket": "1", - "initialLeverage": "20", - "notionalCap": "50000", - "notionalFloor": "0", - "maintMarginRatio": "0.02", - "cum": "0.0" - } - }, - { - "tier": 2.0, - "currency": "USDT", - "minNotional": 50000.0, - "maxNotional": 150000.0, - "maintenanceMarginRate": 0.025, - "maxLeverage": 10.0, - "info": { - "bracket": "2", - "initialLeverage": "10", - "notionalCap": "150000", - "notionalFloor": "50000", - "maintMarginRatio": "0.025", - "cum": "250.0" - } - }, - { - "tier": 3.0, - "currency": "USDT", - "minNotional": 150000.0, - "maxNotional": 250000.0, - "maintenanceMarginRate": 0.05, - "maxLeverage": 8.0, - "info": { - "bracket": "3", - "initialLeverage": "8", - "notionalCap": "250000", - "notionalFloor": "150000", - "maintMarginRatio": "0.05", - "cum": "4000.0" - } - }, - { - "tier": 4.0, - "currency": "USDT", - "minNotional": 250000.0, + "minNotional": 200000.0, "maxNotional": 500000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, @@ -8095,9 +8485,9 @@ "bracket": "4", "initialLeverage": "5", "notionalCap": "500000", - "notionalFloor": "250000", + "notionalFloor": "200000", "maintMarginRatio": "0.1", - "cum": "16500.0" + "cum": "10650.0" } }, { @@ -8113,39 +8503,169 @@ "notionalCap": "1000000", "notionalFloor": "500000", "maintMarginRatio": "0.125", - "cum": "29000.0" + "cum": "23150.0" } }, { "tier": 6.0, "currency": "USDT", "minNotional": 1000000.0, - "maxNotional": 4000000.0, + "maxNotional": 3000000.0, "maintenanceMarginRate": 0.25, "maxLeverage": 2.0, "info": { "bracket": "6", "initialLeverage": "2", - "notionalCap": "4000000", + "notionalCap": "3000000", "notionalFloor": "1000000", "maintMarginRatio": "0.25", - "cum": "154000.0" + "cum": "148150.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 3000000.0, + "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "7", + "initialLeverage": "1", + "notionalCap": "5000000", + "notionalFloor": "3000000", + "maintMarginRatio": "0.5", + "cum": "898150.0" + } + } + ], + "DYDX/USDT:USDT": [ + { + "tier": 1.0, + "currency": "USDT", + "minNotional": 0.0, + "maxNotional": 5000.0, + "maintenanceMarginRate": 0.01, + "maxLeverage": 50.0, + "info": { + "bracket": "1", + "initialLeverage": "50", + "notionalCap": "5000", + "notionalFloor": "0", + "maintMarginRatio": "0.01", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "USDT", + "minNotional": 5000.0, + "maxNotional": 50000.0, + "maintenanceMarginRate": 0.02, + "maxLeverage": 25.0, + "info": { + "bracket": "2", + "initialLeverage": "25", + "notionalCap": "50000", + "notionalFloor": "5000", + "maintMarginRatio": "0.02", + "cum": "50.0" + } + }, + { + "tier": 3.0, + "currency": "USDT", + "minNotional": 50000.0, + "maxNotional": 400000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 20.0, + "info": { + "bracket": "3", + "initialLeverage": "20", + "notionalCap": "400000", + "notionalFloor": "50000", + "maintMarginRatio": "0.025", + "cum": "300.0" + } + }, + { + "tier": 4.0, + "currency": "USDT", + "minNotional": 400000.0, + "maxNotional": 800000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "4", + "initialLeverage": "10", + "notionalCap": "800000", + "notionalFloor": "400000", + "maintMarginRatio": "0.05", + "cum": "10300.0" + } + }, + { + "tier": 5.0, + "currency": "USDT", + "minNotional": 800000.0, + "maxNotional": 2000000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "5", + "initialLeverage": "5", + "notionalCap": "2000000", + "notionalFloor": "800000", + "maintMarginRatio": "0.1", + "cum": "50300.0" + } + }, + { + "tier": 6.0, + "currency": "USDT", + "minNotional": 2000000.0, + "maxNotional": 4000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 4.0, + "info": { + "bracket": "6", + "initialLeverage": "4", + "notionalCap": "4000000", + "notionalFloor": "2000000", + "maintMarginRatio": "0.125", + "cum": "100300.0" } }, { "tier": 7.0, "currency": "USDT", "minNotional": 4000000.0, - "maxNotional": 8000000.0, + "maxNotional": 12000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "7", + "initialLeverage": "2", + "notionalCap": "12000000", + "notionalFloor": "4000000", + "maintMarginRatio": "0.25", + "cum": "600300.0" + } + }, + { + "tier": 8.0, + "currency": "USDT", + "minNotional": 12000000.0, + "maxNotional": 20000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "7", + "bracket": "8", "initialLeverage": "1", - "notionalCap": "8000000", - "notionalFloor": "4000000", + "notionalCap": "20000000", + "notionalFloor": "12000000", "maintMarginRatio": "0.5", - "cum": "1154000.0" + "cum": "3600300.0" } } ], @@ -9096,13 +9616,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 250000.0, - "maxNotional": 1000000.0, + "maxNotional": 2000000.0, "maintenanceMarginRate": 0.01, "maxLeverage": 50.0, "info": { "bracket": "3", "initialLeverage": "50", - "notionalCap": "1000000", + "notionalCap": "2000000", "notionalFloor": "250000", "maintMarginRatio": "0.01", "cum": "1025.0" @@ -9111,71 +9631,71 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 1000000.0, - "maxNotional": 5000000.0, + "minNotional": 2000000.0, + "maxNotional": 10000000.0, "maintenanceMarginRate": 0.02, "maxLeverage": 20.0, "info": { "bracket": "4", "initialLeverage": "20", - "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalCap": "10000000", + "notionalFloor": "2000000", "maintMarginRatio": "0.02", - "cum": "11025.0" + "cum": "21025.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 5000000.0, - "maxNotional": 10000000.0, + "minNotional": 10000000.0, + "maxNotional": 25000000.0, "maintenanceMarginRate": 0.05, "maxLeverage": 10.0, "info": { "bracket": "5", "initialLeverage": "10", - "notionalCap": "10000000", - "notionalFloor": "5000000", + "notionalCap": "25000000", + "notionalFloor": "10000000", "maintMarginRatio": "0.05", - "cum": "161025.0" + "cum": "321025.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 10000000.0, - "maxNotional": 20000000.0, + "minNotional": 25000000.0, + "maxNotional": 50000000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "6", "initialLeverage": "5", - "notionalCap": "20000000", - "notionalFloor": "10000000", + "notionalCap": "50000000", + "notionalFloor": "25000000", "maintMarginRatio": "0.1", - "cum": "661025.0" + "cum": "1571025.0" } }, { "tier": 7.0, "currency": "USDT", - "minNotional": 20000000.0, - "maxNotional": 40000000.0, + "minNotional": 50000000.0, + "maxNotional": 60000000.0, "maintenanceMarginRate": 0.125, "maxLeverage": 4.0, "info": { "bracket": "7", "initialLeverage": "4", - "notionalCap": "40000000", - "notionalFloor": "20000000", + "notionalCap": "60000000", + "notionalFloor": "50000000", "maintMarginRatio": "0.125", - "cum": "1161025.0" + "cum": "2821025.0" } }, { "tier": 8.0, "currency": "USDT", - "minNotional": 40000000.0, + "minNotional": 60000000.0, "maxNotional": 80000000.0, "maintenanceMarginRate": 0.15, "maxLeverage": 3.0, @@ -9183,9 +9703,9 @@ "bracket": "8", "initialLeverage": "3", "notionalCap": "80000000", - "notionalFloor": "40000000", + "notionalFloor": "60000000", "maintMarginRatio": "0.15", - "cum": "2161025.0" + "cum": "4321025.0" } }, { @@ -9201,7 +9721,7 @@ "notionalCap": "150000000", "notionalFloor": "80000000", "maintMarginRatio": "0.25", - "cum": "1.0161025E7" + "cum": "1.2321025E7" } }, { @@ -9217,7 +9737,7 @@ "notionalCap": "300000000", "notionalFloor": "150000000", "maintMarginRatio": "0.5", - "cum": "4.7661025E7" + "cum": "4.9821025E7" } } ], @@ -9342,10 +9862,10 @@ "minNotional": 0.0, "maxNotional": 5000.0, "maintenanceMarginRate": 0.02, - "maxLeverage": 20.0, + "maxLeverage": 25.0, "info": { "bracket": "1", - "initialLeverage": "20", + "initialLeverage": "25", "notionalCap": "5000", "notionalFloor": "0", "maintMarginRatio": "0.02", @@ -9358,10 +9878,10 @@ "minNotional": 5000.0, "maxNotional": 25000.0, "maintenanceMarginRate": 0.025, - "maxLeverage": 15.0, + "maxLeverage": 20.0, "info": { "bracket": "2", - "initialLeverage": "15", + "initialLeverage": "20", "notionalCap": "25000", "notionalFloor": "5000", "maintMarginRatio": "0.025", @@ -9372,13 +9892,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, + "maxNotional": 200000.0, "maintenanceMarginRate": 0.05, "maxLeverage": 10.0, "info": { "bracket": "3", "initialLeverage": "10", - "notionalCap": "100000", + "notionalCap": "200000", "notionalFloor": "25000", "maintMarginRatio": "0.05", "cum": "650.0" @@ -9387,49 +9907,65 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, + "minNotional": 200000.0, + "maxNotional": 500000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "4", "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", + "notionalCap": "500000", + "notionalFloor": "200000", "maintMarginRatio": "0.1", - "cum": "5650.0" + "cum": "10650.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, + "minNotional": 500000.0, "maxNotional": 1000000.0, "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maxLeverage": 4.0, "info": { "bracket": "5", - "initialLeverage": "2", + "initialLeverage": "4", "notionalCap": "1000000", - "notionalFloor": "250000", + "notionalFloor": "500000", "maintMarginRatio": "0.125", - "cum": "11900.0" + "cum": "23150.0" } }, { "tier": 6.0, "currency": "USDT", "minNotional": 1000000.0, + "maxNotional": 3000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "3000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.25", + "cum": "148150.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 3000000.0, "maxNotional": 5000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "7", "initialLeverage": "1", "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalFloor": "3000000", "maintMarginRatio": "0.5", - "cum": "386900.0" + "cum": "898150.0" } } ], @@ -9537,14 +10073,14 @@ "currency": "USDT", "minNotional": 0.0, "maxNotional": 50000.0, - "maintenanceMarginRate": 0.01, - "maxLeverage": 25.0, + "maintenanceMarginRate": 0.006, + "maxLeverage": 50.0, "info": { "bracket": "1", - "initialLeverage": "25", + "initialLeverage": "50", "notionalCap": "50000", "notionalFloor": "0", - "maintMarginRatio": "0.01", + "maintMarginRatio": "0.006", "cum": "0.0" } }, @@ -9553,111 +10089,127 @@ "currency": "USDT", "minNotional": 50000.0, "maxNotional": 250000.0, - "maintenanceMarginRate": 0.02, - "maxLeverage": 20.0, + "maintenanceMarginRate": 0.01, + "maxLeverage": 25.0, "info": { "bracket": "2", - "initialLeverage": "20", + "initialLeverage": "25", "notionalCap": "250000", "notionalFloor": "50000", - "maintMarginRatio": "0.02", - "cum": "500.0" + "maintMarginRatio": "0.01", + "cum": "200.0" } }, { "tier": 3.0, "currency": "USDT", "minNotional": 250000.0, - "maxNotional": 1000000.0, - "maintenanceMarginRate": 0.05, - "maxLeverage": 10.0, + "maxNotional": 600000.0, + "maintenanceMarginRate": 0.02, + "maxLeverage": 20.0, "info": { "bracket": "3", - "initialLeverage": "10", - "notionalCap": "1000000", + "initialLeverage": "20", + "notionalCap": "600000", "notionalFloor": "250000", - "maintMarginRatio": "0.05", - "cum": "8000.0" + "maintMarginRatio": "0.02", + "cum": "2700.0" } }, { "tier": 4.0, "currency": "USDT", - "minNotional": 1000000.0, - "maxNotional": 2000000.0, - "maintenanceMarginRate": 0.1, - "maxLeverage": 5.0, + "minNotional": 600000.0, + "maxNotional": 1200000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, "info": { "bracket": "4", - "initialLeverage": "5", - "notionalCap": "2000000", - "notionalFloor": "1000000", - "maintMarginRatio": "0.1", - "cum": "58000.0" + "initialLeverage": "10", + "notionalCap": "1200000", + "notionalFloor": "600000", + "maintMarginRatio": "0.05", + "cum": "20700.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 2000000.0, - "maxNotional": 5000000.0, - "maintenanceMarginRate": 0.125, - "maxLeverage": 4.0, + "minNotional": 1200000.0, + "maxNotional": 3000000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, "info": { "bracket": "5", - "initialLeverage": "4", - "notionalCap": "5000000", - "notionalFloor": "2000000", - "maintMarginRatio": "0.125", - "cum": "108000.0" + "initialLeverage": "5", + "notionalCap": "3000000", + "notionalFloor": "1200000", + "maintMarginRatio": "0.1", + "cum": "80700.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 5000000.0, - "maxNotional": 10000000.0, - "maintenanceMarginRate": 0.1665, - "maxLeverage": 3.0, + "minNotional": 3000000.0, + "maxNotional": 6000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 4.0, "info": { "bracket": "6", - "initialLeverage": "3", - "notionalCap": "10000000", - "notionalFloor": "5000000", - "maintMarginRatio": "0.1665", - "cum": "315500.0" + "initialLeverage": "4", + "notionalCap": "6000000", + "notionalFloor": "3000000", + "maintMarginRatio": "0.125", + "cum": "155700.0" } }, { "tier": 7.0, "currency": "USDT", + "minNotional": 6000000.0, + "maxNotional": 10000000.0, + "maintenanceMarginRate": 0.165, + "maxLeverage": 3.0, + "info": { + "bracket": "7", + "initialLeverage": "3", + "notionalCap": "10000000", + "notionalFloor": "6000000", + "maintMarginRatio": "0.165", + "cum": "395700.0" + } + }, + { + "tier": 8.0, + "currency": "USDT", "minNotional": 10000000.0, "maxNotional": 20000000.0, "maintenanceMarginRate": 0.25, "maxLeverage": 2.0, "info": { - "bracket": "7", + "bracket": "8", "initialLeverage": "2", "notionalCap": "20000000", "notionalFloor": "10000000", "maintMarginRatio": "0.25", - "cum": "1150500.0" + "cum": "1245700.0" } }, { - "tier": 8.0, + "tier": 9.0, "currency": "USDT", "minNotional": 20000000.0, "maxNotional": 30000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "8", + "bracket": "9", "initialLeverage": "1", "notionalCap": "30000000", "notionalFloor": "20000000", "maintMarginRatio": "0.5", - "cum": "6150500.0" + "cum": "6245700.0" } } ], @@ -10075,14 +10627,14 @@ "currency": "USDT", "minNotional": 0.0, "maxNotional": 5000.0, - "maintenanceMarginRate": 0.0075, + "maintenanceMarginRate": 0.006, "maxLeverage": 50.0, "info": { "bracket": "1", "initialLeverage": "50", "notionalCap": "5000", "notionalFloor": "0", - "maintMarginRatio": "0.0075", + "maintMarginRatio": "0.006", "cum": "0.0" } }, @@ -10099,103 +10651,103 @@ "notionalCap": "50000", "notionalFloor": "5000", "maintMarginRatio": "0.01", - "cum": "12.5" + "cum": "20.0" } }, { "tier": 3.0, "currency": "USDT", "minNotional": 50000.0, - "maxNotional": 150000.0, + "maxNotional": 400000.0, "maintenanceMarginRate": 0.025, "maxLeverage": 20.0, "info": { "bracket": "3", "initialLeverage": "20", - "notionalCap": "150000", + "notionalCap": "400000", "notionalFloor": "50000", "maintMarginRatio": "0.025", - "cum": "762.5" + "cum": "770.0" } }, { "tier": 4.0, "currency": "USDT", - "minNotional": 150000.0, - "maxNotional": 250000.0, + "minNotional": 400000.0, + "maxNotional": 800000.0, "maintenanceMarginRate": 0.05, "maxLeverage": 10.0, "info": { "bracket": "4", "initialLeverage": "10", - "notionalCap": "250000", - "notionalFloor": "150000", + "notionalCap": "800000", + "notionalFloor": "400000", "maintMarginRatio": "0.05", - "cum": "4512.5" + "cum": "10770.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, - "maxNotional": 500000.0, + "minNotional": 800000.0, + "maxNotional": 2000000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "5", "initialLeverage": "5", - "notionalCap": "500000", - "notionalFloor": "250000", + "notionalCap": "2000000", + "notionalFloor": "800000", "maintMarginRatio": "0.1", - "cum": "17012.5" + "cum": "50770.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 500000.0, - "maxNotional": 1000000.0, + "minNotional": 2000000.0, + "maxNotional": 5000000.0, "maintenanceMarginRate": 0.125, "maxLeverage": 4.0, "info": { "bracket": "6", "initialLeverage": "4", - "notionalCap": "1000000", - "notionalFloor": "500000", + "notionalCap": "5000000", + "notionalFloor": "2000000", "maintMarginRatio": "0.125", - "cum": "29512.5" + "cum": "100770.0" } }, { "tier": 7.0, "currency": "USDT", - "minNotional": 1000000.0, - "maxNotional": 4000000.0, + "minNotional": 5000000.0, + "maxNotional": 12000000.0, "maintenanceMarginRate": 0.25, "maxLeverage": 2.0, "info": { "bracket": "7", "initialLeverage": "2", - "notionalCap": "4000000", - "notionalFloor": "1000000", + "notionalCap": "12000000", + "notionalFloor": "5000000", "maintMarginRatio": "0.25", - "cum": "154512.5" + "cum": "725770.0" } }, { "tier": 8.0, "currency": "USDT", - "minNotional": 4000000.0, - "maxNotional": 10000000.0, + "minNotional": 12000000.0, + "maxNotional": 20000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { "bracket": "8", "initialLeverage": "1", - "notionalCap": "10000000", - "notionalFloor": "4000000", + "notionalCap": "20000000", + "notionalFloor": "12000000", "maintMarginRatio": "0.5", - "cum": "1154512.5" + "cum": "3725770.0" } } ], @@ -11113,6 +11665,104 @@ } } ], + "GMX/USDT:USDT": [ + { + "tier": 1.0, + "currency": "USDT", + "minNotional": 0.0, + "maxNotional": 5000.0, + "maintenanceMarginRate": 0.02, + "maxLeverage": 20.0, + "info": { + "bracket": "1", + "initialLeverage": "20", + "notionalCap": "5000", + "notionalFloor": "0", + "maintMarginRatio": "0.02", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "USDT", + "minNotional": 5000.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 15.0, + "info": { + "bracket": "2", + "initialLeverage": "15", + "notionalCap": "25000", + "notionalFloor": "5000", + "maintMarginRatio": "0.025", + "cum": "25.0" + } + }, + { + "tier": 3.0, + "currency": "USDT", + "minNotional": 25000.0, + "maxNotional": 100000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "3", + "initialLeverage": "10", + "notionalCap": "100000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "650.0" + } + }, + { + "tier": 4.0, + "currency": "USDT", + "minNotional": 100000.0, + "maxNotional": 250000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "4", + "initialLeverage": "5", + "notionalCap": "250000", + "notionalFloor": "100000", + "maintMarginRatio": "0.1", + "cum": "5650.0" + } + }, + { + "tier": 5.0, + "currency": "USDT", + "minNotional": 250000.0, + "maxNotional": 1000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 2.0, + "info": { + "bracket": "5", + "initialLeverage": "2", + "notionalCap": "1000000", + "notionalFloor": "250000", + "maintMarginRatio": "0.125", + "cum": "11900.0" + } + }, + { + "tier": 6.0, + "currency": "USDT", + "minNotional": 1000000.0, + "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "6", + "initialLeverage": "1", + "notionalCap": "5000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.5", + "cum": "386900.0" + } + } + ], "GRT/USDT:USDT": [ { "tier": 1.0, @@ -11150,13 +11800,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, + "maxNotional": 400000.0, "maintenanceMarginRate": 0.05, "maxLeverage": 10.0, "info": { "bracket": "3", "initialLeverage": "10", - "notionalCap": "100000", + "notionalCap": "400000", "notionalFloor": "25000", "maintMarginRatio": "0.05", "cum": "700.0" @@ -11165,49 +11815,65 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, + "minNotional": 400000.0, + "maxNotional": 1000000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "4", "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", + "notionalCap": "1000000", + "notionalFloor": "400000", "maintMarginRatio": "0.1", - "cum": "5700.0" + "cum": "20700.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, - "maxNotional": 1000000.0, + "minNotional": 1000000.0, + "maxNotional": 2000000.0, "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maxLeverage": 4.0, "info": { "bracket": "5", - "initialLeverage": "2", - "notionalCap": "1000000", - "notionalFloor": "250000", + "initialLeverage": "4", + "notionalCap": "2000000", + "notionalFloor": "1000000", "maintMarginRatio": "0.125", - "cum": "11950.0" + "cum": "45700.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 1000000.0, - "maxNotional": 5000000.0, + "minNotional": 2000000.0, + "maxNotional": 6000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "6000000", + "notionalFloor": "2000000", + "maintMarginRatio": "0.25", + "cum": "295700.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 6000000.0, + "maxNotional": 10000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "7", "initialLeverage": "1", - "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalCap": "10000000", + "notionalFloor": "6000000", "maintMarginRatio": "0.5", - "cum": "386950.0" + "cum": "1795700.0" } } ], @@ -11414,10 +12080,10 @@ "minNotional": 0.0, "maxNotional": 5000.0, "maintenanceMarginRate": 0.02, - "maxLeverage": 20.0, + "maxLeverage": 25.0, "info": { "bracket": "1", - "initialLeverage": "20", + "initialLeverage": "25", "notionalCap": "5000", "notionalFloor": "0", "maintMarginRatio": "0.02", @@ -11430,10 +12096,10 @@ "minNotional": 5000.0, "maxNotional": 25000.0, "maintenanceMarginRate": 0.025, - "maxLeverage": 15.0, + "maxLeverage": 20.0, "info": { "bracket": "2", - "initialLeverage": "15", + "initialLeverage": "20", "notionalCap": "25000", "notionalFloor": "5000", "maintMarginRatio": "0.025", @@ -11444,13 +12110,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, + "maxNotional": 400000.0, "maintenanceMarginRate": 0.05, "maxLeverage": 10.0, "info": { "bracket": "3", "initialLeverage": "10", - "notionalCap": "100000", + "notionalCap": "400000", "notionalFloor": "25000", "maintMarginRatio": "0.05", "cum": "650.0" @@ -11459,49 +12125,65 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, + "minNotional": 400000.0, + "maxNotional": 1000000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "4", "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", + "notionalCap": "1000000", + "notionalFloor": "400000", "maintMarginRatio": "0.1", - "cum": "5650.0" + "cum": "20650.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, - "maxNotional": 1000000.0, + "minNotional": 1000000.0, + "maxNotional": 2000000.0, "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maxLeverage": 4.0, "info": { "bracket": "5", - "initialLeverage": "2", - "notionalCap": "1000000", - "notionalFloor": "250000", + "initialLeverage": "4", + "notionalCap": "2000000", + "notionalFloor": "1000000", "maintMarginRatio": "0.125", - "cum": "11900.0" + "cum": "45650.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 1000000.0, - "maxNotional": 5000000.0, + "minNotional": 2000000.0, + "maxNotional": 6000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "6000000", + "notionalFloor": "2000000", + "maintMarginRatio": "0.25", + "cum": "295650.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 6000000.0, + "maxNotional": 10000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "7", "initialLeverage": "1", - "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalCap": "10000000", + "notionalFloor": "6000000", "maintMarginRatio": "0.5", - "cum": "386900.0" + "cum": "1795650.0" } } ], @@ -12296,10 +12978,10 @@ "minNotional": 0.0, "maxNotional": 5000.0, "maintenanceMarginRate": 0.02, - "maxLeverage": 20.0, + "maxLeverage": 25.0, "info": { "bracket": "1", - "initialLeverage": "20", + "initialLeverage": "25", "notionalCap": "5000", "notionalFloor": "0", "maintMarginRatio": "0.02", @@ -12312,10 +12994,10 @@ "minNotional": 5000.0, "maxNotional": 25000.0, "maintenanceMarginRate": 0.025, - "maxLeverage": 10.0, + "maxLeverage": 20.0, "info": { "bracket": "2", - "initialLeverage": "10", + "initialLeverage": "20", "notionalCap": "25000", "notionalFloor": "5000", "maintMarginRatio": "0.025", @@ -12326,13 +13008,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, + "maxNotional": 200000.0, "maintenanceMarginRate": 0.05, - "maxLeverage": 8.0, + "maxLeverage": 10.0, "info": { "bracket": "3", - "initialLeverage": "8", - "notionalCap": "100000", + "initialLeverage": "10", + "notionalCap": "200000", "notionalFloor": "25000", "maintMarginRatio": "0.05", "cum": "650.0" @@ -12341,33 +13023,33 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, + "minNotional": 200000.0, + "maxNotional": 500000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "4", "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", + "notionalCap": "500000", + "notionalFloor": "200000", "maintMarginRatio": "0.1", - "cum": "5650.0" + "cum": "10650.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, + "minNotional": 500000.0, "maxNotional": 1000000.0, "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maxLeverage": 4.0, "info": { "bracket": "5", - "initialLeverage": "2", + "initialLeverage": "4", "notionalCap": "1000000", - "notionalFloor": "250000", + "notionalFloor": "500000", "maintMarginRatio": "0.125", - "cum": "11900.0" + "cum": "23150.0" } }, { @@ -12375,15 +13057,31 @@ "currency": "USDT", "minNotional": 1000000.0, "maxNotional": 3000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "3000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.25", + "cum": "148150.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 3000000.0, + "maxNotional": 5000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "7", "initialLeverage": "1", - "notionalCap": "3000000", - "notionalFloor": "1000000", + "notionalCap": "5000000", + "notionalFloor": "3000000", "maintMarginRatio": "0.5", - "cum": "386900.0" + "cum": "898150.0" } } ], @@ -12800,80 +13498,112 @@ "tier": 1.0, "currency": "USDT", "minNotional": 0.0, - "maxNotional": 25000.0, - "maintenanceMarginRate": 0.025, - "maxLeverage": 20.0, + "maxNotional": 5000.0, + "maintenanceMarginRate": 0.01, + "maxLeverage": 25.0, "info": { "bracket": "1", - "initialLeverage": "20", - "notionalCap": "25000", + "initialLeverage": "25", + "notionalCap": "5000", "notionalFloor": "0", - "maintMarginRatio": "0.025", + "maintMarginRatio": "0.01", "cum": "0.0" } }, { "tier": 2.0, "currency": "USDT", - "minNotional": 25000.0, - "maxNotional": 100000.0, - "maintenanceMarginRate": 0.05, - "maxLeverage": 10.0, + "minNotional": 5000.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 20.0, "info": { "bracket": "2", - "initialLeverage": "10", - "notionalCap": "100000", - "notionalFloor": "25000", - "maintMarginRatio": "0.05", - "cum": "625.0" + "initialLeverage": "20", + "notionalCap": "25000", + "notionalFloor": "5000", + "maintMarginRatio": "0.025", + "cum": "75.0" } }, { "tier": 3.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, - "maintenanceMarginRate": 0.1, - "maxLeverage": 5.0, + "minNotional": 25000.0, + "maxNotional": 400000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, "info": { "bracket": "3", - "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", - "maintMarginRatio": "0.1", - "cum": "5625.0" + "initialLeverage": "10", + "notionalCap": "400000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "700.0" } }, { "tier": 4.0, "currency": "USDT", - "minNotional": 250000.0, + "minNotional": 400000.0, "maxNotional": 1000000.0, - "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, "info": { "bracket": "4", - "initialLeverage": "2", + "initialLeverage": "5", "notionalCap": "1000000", - "notionalFloor": "250000", - "maintMarginRatio": "0.125", - "cum": "11875.0" + "notionalFloor": "400000", + "maintMarginRatio": "0.1", + "cum": "20700.0" } }, { "tier": 5.0, "currency": "USDT", "minNotional": 1000000.0, - "maxNotional": 5000000.0, + "maxNotional": 2000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 4.0, + "info": { + "bracket": "5", + "initialLeverage": "4", + "notionalCap": "2000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.125", + "cum": "45700.0" + } + }, + { + "tier": 6.0, + "currency": "USDT", + "minNotional": 2000000.0, + "maxNotional": 6000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "6000000", + "notionalFloor": "2000000", + "maintMarginRatio": "0.25", + "cum": "295700.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 6000000.0, + "maxNotional": 10000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "5", + "bracket": "7", "initialLeverage": "1", - "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalCap": "10000000", + "notionalFloor": "6000000", "maintMarginRatio": "0.5", - "cum": "386875.0" + "cum": "1795700.0" } } ], @@ -13177,14 +13907,14 @@ "currency": "USDT", "minNotional": 0.0, "maxNotional": 5000.0, - "maintenanceMarginRate": 0.01, - "maxLeverage": 20.0, + "maintenanceMarginRate": 0.006, + "maxLeverage": 50.0, "info": { "bracket": "1", - "initialLeverage": "20", + "initialLeverage": "50", "notionalCap": "5000", "notionalFloor": "0", - "maintMarginRatio": "0.01", + "maintMarginRatio": "0.006", "cum": "0.0" } }, @@ -13192,80 +13922,112 @@ "tier": 2.0, "currency": "USDT", "minNotional": 5000.0, - "maxNotional": 25000.0, - "maintenanceMarginRate": 0.025, - "maxLeverage": 10.0, + "maxNotional": 50000.0, + "maintenanceMarginRate": 0.01, + "maxLeverage": 25.0, "info": { "bracket": "2", - "initialLeverage": "10", - "notionalCap": "25000", + "initialLeverage": "25", + "notionalCap": "50000", "notionalFloor": "5000", - "maintMarginRatio": "0.025", - "cum": "75.0" + "maintMarginRatio": "0.01", + "cum": "20.0" } }, { "tier": 3.0, "currency": "USDT", - "minNotional": 25000.0, - "maxNotional": 100000.0, - "maintenanceMarginRate": 0.05, - "maxLeverage": 8.0, + "minNotional": 50000.0, + "maxNotional": 400000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 20.0, "info": { "bracket": "3", - "initialLeverage": "8", - "notionalCap": "100000", - "notionalFloor": "25000", - "maintMarginRatio": "0.05", - "cum": "700.0" + "initialLeverage": "20", + "notionalCap": "400000", + "notionalFloor": "50000", + "maintMarginRatio": "0.025", + "cum": "770.0" } }, { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, - "maintenanceMarginRate": 0.1, - "maxLeverage": 5.0, + "minNotional": 400000.0, + "maxNotional": 800000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, "info": { "bracket": "4", - "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", - "maintMarginRatio": "0.1", - "cum": "5700.0" + "initialLeverage": "10", + "notionalCap": "800000", + "notionalFloor": "400000", + "maintMarginRatio": "0.05", + "cum": "10770.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, - "maxNotional": 1000000.0, - "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "minNotional": 800000.0, + "maxNotional": 2000000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, "info": { "bracket": "5", - "initialLeverage": "2", - "notionalCap": "1000000", - "notionalFloor": "250000", - "maintMarginRatio": "0.125", - "cum": "11950.0" + "initialLeverage": "5", + "notionalCap": "2000000", + "notionalFloor": "800000", + "maintMarginRatio": "0.1", + "cum": "50770.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 1000000.0, + "minNotional": 2000000.0, "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 4.0, + "info": { + "bracket": "6", + "initialLeverage": "4", + "notionalCap": "5000000", + "notionalFloor": "2000000", + "maintMarginRatio": "0.125", + "cum": "100770.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 5000000.0, + "maxNotional": 12000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "7", + "initialLeverage": "2", + "notionalCap": "12000000", + "notionalFloor": "5000000", + "maintMarginRatio": "0.25", + "cum": "725770.0" + } + }, + { + "tier": 8.0, + "currency": "USDT", + "minNotional": 12000000.0, + "maxNotional": 20000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "8", "initialLeverage": "1", - "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalCap": "20000000", + "notionalFloor": "12000000", "maintMarginRatio": "0.5", - "cum": "386950.0" + "cum": "3725770.0" } } ], @@ -13921,6 +14683,120 @@ } } ], + "LQTY/USDT:USDT": [ + { + "tier": 1.0, + "currency": "USDT", + "minNotional": 0.0, + "maxNotional": 5000.0, + "maintenanceMarginRate": 0.02, + "maxLeverage": 20.0, + "info": { + "bracket": "1", + "initialLeverage": "20", + "notionalCap": "5000", + "notionalFloor": "0", + "maintMarginRatio": "0.02", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "USDT", + "minNotional": 5000.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 15.0, + "info": { + "bracket": "2", + "initialLeverage": "15", + "notionalCap": "25000", + "notionalFloor": "5000", + "maintMarginRatio": "0.025", + "cum": "25.0" + } + }, + { + "tier": 3.0, + "currency": "USDT", + "minNotional": 25000.0, + "maxNotional": 200000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "3", + "initialLeverage": "10", + "notionalCap": "200000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "650.0" + } + }, + { + "tier": 4.0, + "currency": "USDT", + "minNotional": 200000.0, + "maxNotional": 500000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "4", + "initialLeverage": "5", + "notionalCap": "500000", + "notionalFloor": "200000", + "maintMarginRatio": "0.1", + "cum": "10650.0" + } + }, + { + "tier": 5.0, + "currency": "USDT", + "minNotional": 500000.0, + "maxNotional": 1000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 4.0, + "info": { + "bracket": "5", + "initialLeverage": "4", + "notionalCap": "1000000", + "notionalFloor": "500000", + "maintMarginRatio": "0.125", + "cum": "23150.0" + } + }, + { + "tier": 6.0, + "currency": "USDT", + "minNotional": 1000000.0, + "maxNotional": 3000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "3000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.25", + "cum": "148150.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 3000000.0, + "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "7", + "initialLeverage": "1", + "notionalCap": "5000000", + "notionalFloor": "3000000", + "maintMarginRatio": "0.5", + "cum": "898150.0" + } + } + ], "LRC/USDT:USDT": [ { "tier": 1.0, @@ -14772,13 +15648,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, + "maxNotional": 600000.0, "maintenanceMarginRate": 0.05, "maxLeverage": 10.0, "info": { "bracket": "3", "initialLeverage": "10", - "notionalCap": "100000", + "notionalCap": "600000", "notionalFloor": "25000", "maintMarginRatio": "0.05", "cum": "650.0" @@ -14787,49 +15663,65 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, + "minNotional": 600000.0, + "maxNotional": 1600000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "4", "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", + "notionalCap": "1600000", + "notionalFloor": "600000", "maintMarginRatio": "0.1", - "cum": "5650.0" + "cum": "30650.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, + "minNotional": 1600000.0, "maxNotional": 3000000.0, "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maxLeverage": 4.0, "info": { "bracket": "5", - "initialLeverage": "2", + "initialLeverage": "4", "notionalCap": "3000000", - "notionalFloor": "250000", + "notionalFloor": "1600000", "maintMarginRatio": "0.125", - "cum": "11900.0" + "cum": "70650.0" } }, { "tier": 6.0, "currency": "USDT", "minNotional": 3000000.0, - "maxNotional": 8000000.0, + "maxNotional": 6000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "6000000", + "notionalFloor": "3000000", + "maintMarginRatio": "0.25", + "cum": "445650.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 6000000.0, + "maxNotional": 10000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "7", "initialLeverage": "1", - "notionalCap": "8000000", - "notionalFloor": "3000000", + "notionalCap": "10000000", + "notionalFloor": "6000000", "maintMarginRatio": "0.5", - "cum": "1136900.0" + "cum": "1945650.0" } } ], @@ -14953,14 +15845,14 @@ "currency": "USDT", "minNotional": 0.0, "maxNotional": 5000.0, - "maintenanceMarginRate": 0.0065, + "maintenanceMarginRate": 0.006, "maxLeverage": 50.0, "info": { "bracket": "1", "initialLeverage": "50", "notionalCap": "5000", "notionalFloor": "0", - "maintMarginRatio": "0.0065", + "maintMarginRatio": "0.006", "cum": "0.0" } }, @@ -14969,14 +15861,14 @@ "currency": "USDT", "minNotional": 5000.0, "maxNotional": 25000.0, - "maintenanceMarginRate": 0.0075, + "maintenanceMarginRate": 0.007, "maxLeverage": 40.0, "info": { "bracket": "2", "initialLeverage": "40", "notionalCap": "25000", "notionalFloor": "5000", - "maintMarginRatio": "0.0075", + "maintMarginRatio": "0.007", "cum": "5.0" } }, @@ -14993,103 +15885,103 @@ "notionalCap": "50000", "notionalFloor": "25000", "maintMarginRatio": "0.01", - "cum": "67.5" + "cum": "80.0" } }, { "tier": 4.0, "currency": "USDT", "minNotional": 50000.0, - "maxNotional": 150000.0, + "maxNotional": 400000.0, "maintenanceMarginRate": 0.025, "maxLeverage": 20.0, "info": { "bracket": "4", "initialLeverage": "20", - "notionalCap": "150000", + "notionalCap": "400000", "notionalFloor": "50000", "maintMarginRatio": "0.025", - "cum": "817.5" + "cum": "830.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 150000.0, - "maxNotional": 250000.0, + "minNotional": 400000.0, + "maxNotional": 800000.0, "maintenanceMarginRate": 0.05, "maxLeverage": 10.0, "info": { "bracket": "5", "initialLeverage": "10", - "notionalCap": "250000", - "notionalFloor": "150000", + "notionalCap": "800000", + "notionalFloor": "400000", "maintMarginRatio": "0.05", - "cum": "4567.5" + "cum": "10830.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 250000.0, - "maxNotional": 500000.0, + "minNotional": 800000.0, + "maxNotional": 2000000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "6", "initialLeverage": "5", - "notionalCap": "500000", - "notionalFloor": "250000", + "notionalCap": "2000000", + "notionalFloor": "800000", "maintMarginRatio": "0.1", - "cum": "17067.5" + "cum": "50830.0" } }, { "tier": 7.0, "currency": "USDT", - "minNotional": 500000.0, - "maxNotional": 750000.0, + "minNotional": 2000000.0, + "maxNotional": 5000000.0, "maintenanceMarginRate": 0.125, "maxLeverage": 4.0, "info": { "bracket": "7", "initialLeverage": "4", - "notionalCap": "750000", - "notionalFloor": "500000", + "notionalCap": "5000000", + "notionalFloor": "2000000", "maintMarginRatio": "0.125", - "cum": "29567.5" + "cum": "100830.0" } }, { "tier": 8.0, "currency": "USDT", - "minNotional": 750000.0, - "maxNotional": 3000000.0, + "minNotional": 5000000.0, + "maxNotional": 12000000.0, "maintenanceMarginRate": 0.25, "maxLeverage": 2.0, "info": { "bracket": "8", "initialLeverage": "2", - "notionalCap": "3000000", - "notionalFloor": "750000", + "notionalCap": "12000000", + "notionalFloor": "5000000", "maintMarginRatio": "0.25", - "cum": "123317.5" + "cum": "725830.0" } }, { "tier": 9.0, "currency": "USDT", - "minNotional": 3000000.0, - "maxNotional": 10000000.0, + "minNotional": 12000000.0, + "maxNotional": 20000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { "bracket": "9", "initialLeverage": "1", - "notionalCap": "10000000", - "notionalFloor": "3000000", + "notionalCap": "20000000", + "notionalFloor": "12000000", "maintMarginRatio": "0.5", - "cum": "873317.5" + "cum": "3725830.0" } } ], @@ -15099,14 +15991,14 @@ "currency": "USDT", "minNotional": 0.0, "maxNotional": 5000.0, - "maintenanceMarginRate": 0.02, - "maxLeverage": 20.0, + "maintenanceMarginRate": 0.01, + "maxLeverage": 25.0, "info": { "bracket": "1", - "initialLeverage": "20", + "initialLeverage": "25", "notionalCap": "5000", "notionalFloor": "0", - "maintMarginRatio": "0.02", + "maintMarginRatio": "0.01", "cum": "0.0" } }, @@ -15116,78 +16008,94 @@ "minNotional": 5000.0, "maxNotional": 25000.0, "maintenanceMarginRate": 0.025, - "maxLeverage": 15.0, + "maxLeverage": 20.0, "info": { "bracket": "2", - "initialLeverage": "15", + "initialLeverage": "20", "notionalCap": "25000", "notionalFloor": "5000", "maintMarginRatio": "0.025", - "cum": "25.0" + "cum": "75.0" } }, { "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, + "maxNotional": 400000.0, "maintenanceMarginRate": 0.05, "maxLeverage": 10.0, "info": { "bracket": "3", "initialLeverage": "10", - "notionalCap": "100000", + "notionalCap": "400000", "notionalFloor": "25000", "maintMarginRatio": "0.05", - "cum": "650.0" + "cum": "700.0" } }, { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, + "minNotional": 400000.0, + "maxNotional": 1000000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "4", "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", + "notionalCap": "1000000", + "notionalFloor": "400000", "maintMarginRatio": "0.1", - "cum": "5650.0" + "cum": "20700.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, - "maxNotional": 1000000.0, + "minNotional": 1000000.0, + "maxNotional": 2000000.0, "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maxLeverage": 4.0, "info": { "bracket": "5", - "initialLeverage": "2", - "notionalCap": "1000000", - "notionalFloor": "250000", + "initialLeverage": "4", + "notionalCap": "2000000", + "notionalFloor": "1000000", "maintMarginRatio": "0.125", - "cum": "11900.0" + "cum": "45700.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 1000000.0, - "maxNotional": 5000000.0, + "minNotional": 2000000.0, + "maxNotional": 6000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "6000000", + "notionalFloor": "2000000", + "maintMarginRatio": "0.25", + "cum": "295700.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 6000000.0, + "maxNotional": 10000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "7", "initialLeverage": "1", - "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalCap": "10000000", + "notionalFloor": "6000000", "maintMarginRatio": "0.5", - "cum": "386900.0" + "cum": "1795700.0" } } ], @@ -15522,13 +16430,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 150000.0, - "maxNotional": 250000.0, + "maxNotional": 600000.0, "maintenanceMarginRate": 0.05, "maxLeverage": 10.0, "info": { "bracket": "3", "initialLeverage": "10", - "notionalCap": "250000", + "notionalCap": "600000", "notionalFloor": "150000", "maintMarginRatio": "0.05", "cum": "4500.0" @@ -15537,65 +16445,65 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 250000.0, - "maxNotional": 500000.0, + "minNotional": 600000.0, + "maxNotional": 1600000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "4", "initialLeverage": "5", - "notionalCap": "500000", - "notionalFloor": "250000", + "notionalCap": "1600000", + "notionalFloor": "600000", "maintMarginRatio": "0.1", - "cum": "17000.0" + "cum": "34500.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 500000.0, - "maxNotional": 1000000.0, + "minNotional": 1600000.0, + "maxNotional": 2000000.0, "maintenanceMarginRate": 0.125, "maxLeverage": 4.0, "info": { "bracket": "5", "initialLeverage": "4", - "notionalCap": "1000000", - "notionalFloor": "500000", + "notionalCap": "2000000", + "notionalFloor": "1600000", "maintMarginRatio": "0.125", - "cum": "29500.0" + "cum": "74500.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 1000000.0, - "maxNotional": 2000000.0, + "minNotional": 2000000.0, + "maxNotional": 6000000.0, "maintenanceMarginRate": 0.25, "maxLeverage": 2.0, "info": { "bracket": "6", "initialLeverage": "2", - "notionalCap": "2000000", - "notionalFloor": "1000000", + "notionalCap": "6000000", + "notionalFloor": "2000000", "maintMarginRatio": "0.25", - "cum": "154500.0" + "cum": "324500.0" } }, { "tier": 7.0, "currency": "USDT", - "minNotional": 2000000.0, - "maxNotional": 5000000.0, + "minNotional": 6000000.0, + "maxNotional": 10000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { "bracket": "7", "initialLeverage": "1", - "notionalCap": "5000000", - "notionalFloor": "2000000", + "notionalCap": "10000000", + "notionalFloor": "6000000", "maintMarginRatio": "0.5", - "cum": "654500.0" + "cum": "1824500.0" } } ], @@ -15605,14 +16513,14 @@ "currency": "USDT", "minNotional": 0.0, "maxNotional": 5000.0, - "maintenanceMarginRate": 0.01, - "maxLeverage": 25.0, + "maintenanceMarginRate": 0.006, + "maxLeverage": 50.0, "info": { "bracket": "1", - "initialLeverage": "25", + "initialLeverage": "50", "notionalCap": "5000", "notionalFloor": "0", - "maintMarginRatio": "0.01", + "maintMarginRatio": "0.006", "cum": "0.0" } }, @@ -15620,80 +16528,112 @@ "tier": 2.0, "currency": "USDT", "minNotional": 5000.0, - "maxNotional": 25000.0, - "maintenanceMarginRate": 0.025, - "maxLeverage": 20.0, + "maxNotional": 50000.0, + "maintenanceMarginRate": 0.01, + "maxLeverage": 25.0, "info": { "bracket": "2", - "initialLeverage": "20", - "notionalCap": "25000", + "initialLeverage": "25", + "notionalCap": "50000", "notionalFloor": "5000", - "maintMarginRatio": "0.025", - "cum": "75.0" + "maintMarginRatio": "0.01", + "cum": "20.0" } }, { "tier": 3.0, "currency": "USDT", - "minNotional": 25000.0, - "maxNotional": 100000.0, - "maintenanceMarginRate": 0.05, - "maxLeverage": 10.0, + "minNotional": 50000.0, + "maxNotional": 400000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 20.0, "info": { "bracket": "3", - "initialLeverage": "10", - "notionalCap": "100000", - "notionalFloor": "25000", - "maintMarginRatio": "0.05", - "cum": "700.0" + "initialLeverage": "20", + "notionalCap": "400000", + "notionalFloor": "50000", + "maintMarginRatio": "0.025", + "cum": "770.0" } }, { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, - "maintenanceMarginRate": 0.1, - "maxLeverage": 5.0, + "minNotional": 400000.0, + "maxNotional": 800000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, "info": { "bracket": "4", - "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", - "maintMarginRatio": "0.1", - "cum": "5700.0" + "initialLeverage": "10", + "notionalCap": "800000", + "notionalFloor": "400000", + "maintMarginRatio": "0.05", + "cum": "10770.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, - "maxNotional": 1000000.0, - "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "minNotional": 800000.0, + "maxNotional": 2000000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, "info": { "bracket": "5", - "initialLeverage": "2", - "notionalCap": "1000000", - "notionalFloor": "250000", - "maintMarginRatio": "0.125", - "cum": "11950.0" + "initialLeverage": "5", + "notionalCap": "2000000", + "notionalFloor": "800000", + "maintMarginRatio": "0.1", + "cum": "50770.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 1000000.0, + "minNotional": 2000000.0, "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 4.0, + "info": { + "bracket": "6", + "initialLeverage": "4", + "notionalCap": "5000000", + "notionalFloor": "2000000", + "maintMarginRatio": "0.125", + "cum": "100770.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 5000000.0, + "maxNotional": 12000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "7", + "initialLeverage": "2", + "notionalCap": "12000000", + "notionalFloor": "5000000", + "maintMarginRatio": "0.25", + "cum": "725770.0" + } + }, + { + "tier": 8.0, + "currency": "USDT", + "minNotional": 12000000.0, + "maxNotional": 20000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "8", "initialLeverage": "1", - "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalCap": "20000000", + "notionalFloor": "12000000", "maintMarginRatio": "0.5", - "cum": "386950.0" + "cum": "3725770.0" } } ], @@ -16291,14 +17231,14 @@ "currency": "USDT", "minNotional": 0.0, "maxNotional": 5000.0, - "maintenanceMarginRate": 0.0065, + "maintenanceMarginRate": 0.006, "maxLeverage": 50.0, "info": { "bracket": "1", "initialLeverage": "50", "notionalCap": "5000", "notionalFloor": "0", - "maintMarginRatio": "0.0065", + "maintMarginRatio": "0.006", "cum": "0.0" } }, @@ -16315,61 +17255,61 @@ "notionalCap": "50000", "notionalFloor": "5000", "maintMarginRatio": "0.01", - "cum": "17.5" + "cum": "20.0" } }, { "tier": 3.0, "currency": "USDT", "minNotional": 50000.0, - "maxNotional": 200000.0, + "maxNotional": 400000.0, "maintenanceMarginRate": 0.025, "maxLeverage": 20.0, "info": { "bracket": "3", "initialLeverage": "20", - "notionalCap": "200000", + "notionalCap": "400000", "notionalFloor": "50000", "maintMarginRatio": "0.025", - "cum": "767.5" + "cum": "770.0" } }, { "tier": 4.0, "currency": "USDT", - "minNotional": 200000.0, - "maxNotional": 400000.0, + "minNotional": 400000.0, + "maxNotional": 800000.0, "maintenanceMarginRate": 0.05, "maxLeverage": 10.0, "info": { "bracket": "4", "initialLeverage": "10", - "notionalCap": "400000", - "notionalFloor": "200000", + "notionalCap": "800000", + "notionalFloor": "400000", "maintMarginRatio": "0.05", - "cum": "5767.5" + "cum": "10770.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 400000.0, - "maxNotional": 1000000.0, + "minNotional": 800000.0, + "maxNotional": 2000000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "5", "initialLeverage": "5", - "notionalCap": "1000000", - "notionalFloor": "400000", + "notionalCap": "2000000", + "notionalFloor": "800000", "maintMarginRatio": "0.1", - "cum": "25767.5" + "cum": "50770.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 1000000.0, + "minNotional": 2000000.0, "maxNotional": 5000000.0, "maintenanceMarginRate": 0.125, "maxLeverage": 4.0, @@ -16377,41 +17317,41 @@ "bracket": "6", "initialLeverage": "4", "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalFloor": "2000000", "maintMarginRatio": "0.125", - "cum": "50767.5" + "cum": "100770.0" } }, { "tier": 7.0, "currency": "USDT", "minNotional": 5000000.0, - "maxNotional": 6000000.0, + "maxNotional": 12000000.0, "maintenanceMarginRate": 0.25, "maxLeverage": 2.0, "info": { "bracket": "7", "initialLeverage": "2", - "notionalCap": "6000000", + "notionalCap": "12000000", "notionalFloor": "5000000", "maintMarginRatio": "0.25", - "cum": "675767.5" + "cum": "725770.0" } }, { "tier": 8.0, "currency": "USDT", - "minNotional": 6000000.0, - "maxNotional": 10000000.0, + "minNotional": 12000000.0, + "maxNotional": 20000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { "bracket": "8", "initialLeverage": "1", - "notionalCap": "10000000", - "notionalFloor": "6000000", + "notionalCap": "20000000", + "notionalFloor": "12000000", "maintMarginRatio": "0.5", - "cum": "2175767.5" + "cum": "3725770.0" } } ], @@ -16513,6 +17453,120 @@ } } ], + "PERP/USDT:USDT": [ + { + "tier": 1.0, + "currency": "USDT", + "minNotional": 0.0, + "maxNotional": 5000.0, + "maintenanceMarginRate": 0.02, + "maxLeverage": 20.0, + "info": { + "bracket": "1", + "initialLeverage": "20", + "notionalCap": "5000", + "notionalFloor": "0", + "maintMarginRatio": "0.02", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "USDT", + "minNotional": 5000.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 15.0, + "info": { + "bracket": "2", + "initialLeverage": "15", + "notionalCap": "25000", + "notionalFloor": "5000", + "maintMarginRatio": "0.025", + "cum": "25.0" + } + }, + { + "tier": 3.0, + "currency": "USDT", + "minNotional": 25000.0, + "maxNotional": 200000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "3", + "initialLeverage": "10", + "notionalCap": "200000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "650.0" + } + }, + { + "tier": 4.0, + "currency": "USDT", + "minNotional": 200000.0, + "maxNotional": 500000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "4", + "initialLeverage": "5", + "notionalCap": "500000", + "notionalFloor": "200000", + "maintMarginRatio": "0.1", + "cum": "10650.0" + } + }, + { + "tier": 5.0, + "currency": "USDT", + "minNotional": 500000.0, + "maxNotional": 1000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 4.0, + "info": { + "bracket": "5", + "initialLeverage": "4", + "notionalCap": "1000000", + "notionalFloor": "500000", + "maintMarginRatio": "0.125", + "cum": "23150.0" + } + }, + { + "tier": 6.0, + "currency": "USDT", + "minNotional": 1000000.0, + "maxNotional": 3000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "3000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.25", + "cum": "148150.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 3000000.0, + "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "7", + "initialLeverage": "1", + "notionalCap": "5000000", + "notionalFloor": "3000000", + "maintMarginRatio": "0.5", + "cum": "898150.0" + } + } + ], "PHB/BUSD:BUSD": [ { "tier": 1.0, @@ -16844,13 +17898,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, + "maxNotional": 200000.0, "maintenanceMarginRate": 0.05, "maxLeverage": 10.0, "info": { "bracket": "3", "initialLeverage": "10", - "notionalCap": "100000", + "notionalCap": "200000", "notionalFloor": "25000", "maintMarginRatio": "0.05", "cum": "700.0" @@ -16859,49 +17913,65 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, + "minNotional": 200000.0, + "maxNotional": 500000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "4", "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", + "notionalCap": "500000", + "notionalFloor": "200000", "maintMarginRatio": "0.1", - "cum": "5700.0" + "cum": "10700.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, + "minNotional": 500000.0, "maxNotional": 1000000.0, "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maxLeverage": 4.0, "info": { "bracket": "5", - "initialLeverage": "2", + "initialLeverage": "4", "notionalCap": "1000000", - "notionalFloor": "250000", + "notionalFloor": "500000", "maintMarginRatio": "0.125", - "cum": "11950.0" + "cum": "23200.0" } }, { "tier": 6.0, "currency": "USDT", "minNotional": 1000000.0, + "maxNotional": 3000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "3000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.25", + "cum": "148200.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 3000000.0, "maxNotional": 5000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "7", "initialLeverage": "1", "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalFloor": "3000000", "maintMarginRatio": "0.5", - "cum": "386950.0" + "cum": "898200.0" } } ], @@ -17108,10 +18178,10 @@ "minNotional": 0.0, "maxNotional": 5000.0, "maintenanceMarginRate": 0.02, - "maxLeverage": 15.0, + "maxLeverage": 25.0, "info": { "bracket": "1", - "initialLeverage": "15", + "initialLeverage": "25", "notionalCap": "5000", "notionalFloor": "0", "maintMarginRatio": "0.02", @@ -17124,10 +18194,10 @@ "minNotional": 5000.0, "maxNotional": 25000.0, "maintenanceMarginRate": 0.025, - "maxLeverage": 10.0, + "maxLeverage": 20.0, "info": { "bracket": "2", - "initialLeverage": "10", + "initialLeverage": "20", "notionalCap": "25000", "notionalFloor": "5000", "maintMarginRatio": "0.025", @@ -17138,13 +18208,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, + "maxNotional": 200000.0, "maintenanceMarginRate": 0.05, - "maxLeverage": 8.0, + "maxLeverage": 10.0, "info": { "bracket": "3", - "initialLeverage": "8", - "notionalCap": "100000", + "initialLeverage": "10", + "notionalCap": "200000", "notionalFloor": "25000", "maintMarginRatio": "0.05", "cum": "650.0" @@ -17153,49 +18223,65 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, + "minNotional": 200000.0, + "maxNotional": 500000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "4", "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", + "notionalCap": "500000", + "notionalFloor": "200000", "maintMarginRatio": "0.1", - "cum": "5650.0" + "cum": "10650.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, + "minNotional": 500000.0, "maxNotional": 1000000.0, "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maxLeverage": 4.0, "info": { "bracket": "5", - "initialLeverage": "2", + "initialLeverage": "4", "notionalCap": "1000000", - "notionalFloor": "250000", + "notionalFloor": "500000", "maintMarginRatio": "0.125", - "cum": "11900.0" + "cum": "23150.0" } }, { "tier": 6.0, "currency": "USDT", "minNotional": 1000000.0, - "maxNotional": 1500000.0, + "maxNotional": 3000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "3000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.25", + "cum": "148150.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 3000000.0, + "maxNotional": 5000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "7", "initialLeverage": "1", - "notionalCap": "1500000", - "notionalFloor": "1000000", + "notionalCap": "5000000", + "notionalFloor": "3000000", "maintMarginRatio": "0.5", - "cum": "386900.0" + "cum": "898150.0" } } ], @@ -17386,10 +18472,10 @@ "minNotional": 0.0, "maxNotional": 5000.0, "maintenanceMarginRate": 0.01, - "maxLeverage": 20.0, + "maxLeverage": 25.0, "info": { "bracket": "1", - "initialLeverage": "20", + "initialLeverage": "25", "notionalCap": "5000", "notionalFloor": "0", "maintMarginRatio": "0.01", @@ -17402,10 +18488,10 @@ "minNotional": 5000.0, "maxNotional": 25000.0, "maintenanceMarginRate": 0.025, - "maxLeverage": 10.0, + "maxLeverage": 20.0, "info": { "bracket": "2", - "initialLeverage": "10", + "initialLeverage": "20", "notionalCap": "25000", "notionalFloor": "5000", "maintMarginRatio": "0.025", @@ -17416,13 +18502,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, + "maxNotional": 200000.0, "maintenanceMarginRate": 0.05, - "maxLeverage": 8.0, + "maxLeverage": 10.0, "info": { "bracket": "3", - "initialLeverage": "8", - "notionalCap": "100000", + "initialLeverage": "10", + "notionalCap": "200000", "notionalFloor": "25000", "maintMarginRatio": "0.05", "cum": "700.0" @@ -17431,49 +18517,65 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, + "minNotional": 200000.0, + "maxNotional": 500000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "4", "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", + "notionalCap": "500000", + "notionalFloor": "200000", "maintMarginRatio": "0.1", - "cum": "5700.0" + "cum": "10700.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, + "minNotional": 500000.0, "maxNotional": 1000000.0, "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maxLeverage": 4.0, "info": { "bracket": "5", - "initialLeverage": "2", + "initialLeverage": "4", "notionalCap": "1000000", - "notionalFloor": "250000", + "notionalFloor": "500000", "maintMarginRatio": "0.125", - "cum": "11950.0" + "cum": "23200.0" } }, { "tier": 6.0, "currency": "USDT", "minNotional": 1000000.0, + "maxNotional": 3000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "3000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.25", + "cum": "148200.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 3000000.0, "maxNotional": 5000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "7", "initialLeverage": "1", "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalFloor": "3000000", "maintMarginRatio": "0.5", - "cum": "386950.0" + "cum": "898200.0" } } ], @@ -17484,10 +18586,10 @@ "minNotional": 0.0, "maxNotional": 5000.0, "maintenanceMarginRate": 0.02, - "maxLeverage": 20.0, + "maxLeverage": 25.0, "info": { "bracket": "1", - "initialLeverage": "20", + "initialLeverage": "25", "notionalCap": "5000", "notionalFloor": "0", "maintMarginRatio": "0.02", @@ -17500,10 +18602,10 @@ "minNotional": 5000.0, "maxNotional": 25000.0, "maintenanceMarginRate": 0.025, - "maxLeverage": 10.0, + "maxLeverage": 20.0, "info": { "bracket": "2", - "initialLeverage": "10", + "initialLeverage": "20", "notionalCap": "25000", "notionalFloor": "5000", "maintMarginRatio": "0.025", @@ -17514,13 +18616,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, + "maxNotional": 300000.0, "maintenanceMarginRate": 0.05, - "maxLeverage": 8.0, + "maxLeverage": 10.0, "info": { "bracket": "3", - "initialLeverage": "8", - "notionalCap": "100000", + "initialLeverage": "10", + "notionalCap": "300000", "notionalFloor": "25000", "maintMarginRatio": "0.05", "cum": "650.0" @@ -17529,49 +18631,65 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, + "minNotional": 300000.0, + "maxNotional": 800000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "4", "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", + "notionalCap": "800000", + "notionalFloor": "300000", "maintMarginRatio": "0.1", - "cum": "5650.0" + "cum": "15650.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, + "minNotional": 800000.0, "maxNotional": 1000000.0, "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maxLeverage": 4.0, "info": { "bracket": "5", - "initialLeverage": "2", + "initialLeverage": "4", "notionalCap": "1000000", - "notionalFloor": "250000", + "notionalFloor": "800000", "maintMarginRatio": "0.125", - "cum": "11900.0" + "cum": "35650.0" } }, { "tier": 6.0, "currency": "USDT", "minNotional": 1000000.0, + "maxNotional": 3000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "3000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.25", + "cum": "160650.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 3000000.0, "maxNotional": 5000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "7", "initialLeverage": "1", "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalFloor": "3000000", "maintMarginRatio": "0.5", - "cum": "386900.0" + "cum": "910650.0" } } ], @@ -17875,14 +18993,14 @@ "currency": "USDT", "minNotional": 0.0, "maxNotional": 5000.0, - "maintenanceMarginRate": 0.0065, + "maintenanceMarginRate": 0.006, "maxLeverage": 50.0, "info": { "bracket": "1", "initialLeverage": "50", "notionalCap": "5000", "notionalFloor": "0", - "maintMarginRatio": "0.0065", + "maintMarginRatio": "0.006", "cum": "0.0" } }, @@ -17891,14 +19009,14 @@ "currency": "USDT", "minNotional": 5000.0, "maxNotional": 25000.0, - "maintenanceMarginRate": 0.0075, + "maintenanceMarginRate": 0.007, "maxLeverage": 40.0, "info": { "bracket": "2", "initialLeverage": "40", "notionalCap": "25000", "notionalFloor": "5000", - "maintMarginRatio": "0.0075", + "maintMarginRatio": "0.007", "cum": "5.0" } }, @@ -17915,103 +19033,103 @@ "notionalCap": "50000", "notionalFloor": "25000", "maintMarginRatio": "0.01", - "cum": "67.5" + "cum": "80.0" } }, { "tier": 4.0, "currency": "USDT", "minNotional": 50000.0, - "maxNotional": 150000.0, + "maxNotional": 400000.0, "maintenanceMarginRate": 0.025, "maxLeverage": 20.0, "info": { "bracket": "4", "initialLeverage": "20", - "notionalCap": "150000", + "notionalCap": "400000", "notionalFloor": "50000", "maintMarginRatio": "0.025", - "cum": "817.5" + "cum": "830.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 150000.0, - "maxNotional": 250000.0, + "minNotional": 400000.0, + "maxNotional": 800000.0, "maintenanceMarginRate": 0.05, "maxLeverage": 10.0, "info": { "bracket": "5", "initialLeverage": "10", - "notionalCap": "250000", - "notionalFloor": "150000", + "notionalCap": "800000", + "notionalFloor": "400000", "maintMarginRatio": "0.05", - "cum": "4567.5" + "cum": "10830.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 250000.0, - "maxNotional": 500000.0, + "minNotional": 800000.0, + "maxNotional": 2000000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "6", "initialLeverage": "5", - "notionalCap": "500000", - "notionalFloor": "250000", + "notionalCap": "2000000", + "notionalFloor": "800000", "maintMarginRatio": "0.1", - "cum": "17067.5" + "cum": "50830.0" } }, { "tier": 7.0, "currency": "USDT", - "minNotional": 500000.0, - "maxNotional": 1000000.0, + "minNotional": 2000000.0, + "maxNotional": 5000000.0, "maintenanceMarginRate": 0.125, "maxLeverage": 4.0, "info": { "bracket": "7", "initialLeverage": "4", - "notionalCap": "1000000", - "notionalFloor": "500000", + "notionalCap": "5000000", + "notionalFloor": "2000000", "maintMarginRatio": "0.125", - "cum": "29567.5" + "cum": "100830.0" } }, { "tier": 8.0, "currency": "USDT", - "minNotional": 1000000.0, - "maxNotional": 5000000.0, + "minNotional": 5000000.0, + "maxNotional": 12000000.0, "maintenanceMarginRate": 0.25, "maxLeverage": 2.0, "info": { "bracket": "8", "initialLeverage": "2", - "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalCap": "12000000", + "notionalFloor": "5000000", "maintMarginRatio": "0.25", - "cum": "154567.5" + "cum": "725830.0" } }, { "tier": 9.0, "currency": "USDT", - "minNotional": 5000000.0, - "maxNotional": 10000000.0, + "minNotional": 12000000.0, + "maxNotional": 20000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { "bracket": "9", "initialLeverage": "1", - "notionalCap": "10000000", - "notionalFloor": "5000000", + "notionalCap": "20000000", + "notionalFloor": "12000000", "maintMarginRatio": "0.5", - "cum": "1404567.5" + "cum": "3725830.0" } } ], @@ -18316,10 +19434,10 @@ "minNotional": 0.0, "maxNotional": 5000.0, "maintenanceMarginRate": 0.01, - "maxLeverage": 20.0, + "maxLeverage": 25.0, "info": { "bracket": "1", - "initialLeverage": "20", + "initialLeverage": "25", "notionalCap": "5000", "notionalFloor": "0", "maintMarginRatio": "0.01", @@ -18332,10 +19450,10 @@ "minNotional": 5000.0, "maxNotional": 25000.0, "maintenanceMarginRate": 0.025, - "maxLeverage": 10.0, + "maxLeverage": 20.0, "info": { "bracket": "2", - "initialLeverage": "10", + "initialLeverage": "20", "notionalCap": "25000", "notionalFloor": "5000", "maintMarginRatio": "0.025", @@ -18346,13 +19464,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, + "maxNotional": 400000.0, "maintenanceMarginRate": 0.05, - "maxLeverage": 8.0, + "maxLeverage": 10.0, "info": { "bracket": "3", - "initialLeverage": "8", - "notionalCap": "100000", + "initialLeverage": "10", + "notionalCap": "400000", "notionalFloor": "25000", "maintMarginRatio": "0.05", "cum": "700.0" @@ -18361,49 +19479,65 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, + "minNotional": 400000.0, + "maxNotional": 1000000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "4", "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", + "notionalCap": "1000000", + "notionalFloor": "400000", "maintMarginRatio": "0.1", - "cum": "5700.0" + "cum": "20700.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, - "maxNotional": 1000000.0, + "minNotional": 1000000.0, + "maxNotional": 2000000.0, "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maxLeverage": 4.0, "info": { "bracket": "5", - "initialLeverage": "2", - "notionalCap": "1000000", - "notionalFloor": "250000", + "initialLeverage": "4", + "notionalCap": "2000000", + "notionalFloor": "1000000", "maintMarginRatio": "0.125", - "cum": "11950.0" + "cum": "45700.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 1000000.0, - "maxNotional": 5000000.0, + "minNotional": 2000000.0, + "maxNotional": 6000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "6000000", + "notionalFloor": "2000000", + "maintMarginRatio": "0.25", + "cum": "295700.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 6000000.0, + "maxNotional": 10000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "7", "initialLeverage": "1", - "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalCap": "10000000", + "notionalFloor": "6000000", "maintMarginRatio": "0.5", - "cum": "386950.0" + "cum": "1795700.0" } } ], @@ -18831,7 +19965,7 @@ } } ], - "STG/USDT:USDT": [ + "SSV/USDT:USDT": [ { "tier": 1.0, "currency": "USDT", @@ -18854,10 +19988,10 @@ "minNotional": 5000.0, "maxNotional": 25000.0, "maintenanceMarginRate": 0.025, - "maxLeverage": 10.0, + "maxLeverage": 15.0, "info": { "bracket": "2", - "initialLeverage": "10", + "initialLeverage": "15", "notionalCap": "25000", "notionalFloor": "5000", "maintMarginRatio": "0.025", @@ -18868,13 +20002,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, + "maxNotional": 200000.0, "maintenanceMarginRate": 0.05, - "maxLeverage": 8.0, + "maxLeverage": 10.0, "info": { "bracket": "3", - "initialLeverage": "8", - "notionalCap": "100000", + "initialLeverage": "10", + "notionalCap": "200000", "notionalFloor": "25000", "maintMarginRatio": "0.05", "cum": "650.0" @@ -18883,33 +20017,33 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, + "minNotional": 200000.0, + "maxNotional": 500000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "4", "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", + "notionalCap": "500000", + "notionalFloor": "200000", "maintMarginRatio": "0.1", - "cum": "5650.0" + "cum": "10650.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, + "minNotional": 500000.0, "maxNotional": 1000000.0, "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maxLeverage": 4.0, "info": { "bracket": "5", - "initialLeverage": "2", + "initialLeverage": "4", "notionalCap": "1000000", - "notionalFloor": "250000", + "notionalFloor": "500000", "maintMarginRatio": "0.125", - "cum": "11900.0" + "cum": "23150.0" } }, { @@ -18917,15 +20051,145 @@ "currency": "USDT", "minNotional": 1000000.0, "maxNotional": 3000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "3000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.25", + "cum": "148150.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 3000000.0, + "maxNotional": 5000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "7", "initialLeverage": "1", + "notionalCap": "5000000", + "notionalFloor": "3000000", + "maintMarginRatio": "0.5", + "cum": "898150.0" + } + } + ], + "STG/USDT:USDT": [ + { + "tier": 1.0, + "currency": "USDT", + "minNotional": 0.0, + "maxNotional": 5000.0, + "maintenanceMarginRate": 0.02, + "maxLeverage": 25.0, + "info": { + "bracket": "1", + "initialLeverage": "25", + "notionalCap": "5000", + "notionalFloor": "0", + "maintMarginRatio": "0.02", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "USDT", + "minNotional": 5000.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 20.0, + "info": { + "bracket": "2", + "initialLeverage": "20", + "notionalCap": "25000", + "notionalFloor": "5000", + "maintMarginRatio": "0.025", + "cum": "25.0" + } + }, + { + "tier": 3.0, + "currency": "USDT", + "minNotional": 25000.0, + "maxNotional": 200000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "3", + "initialLeverage": "10", + "notionalCap": "200000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "650.0" + } + }, + { + "tier": 4.0, + "currency": "USDT", + "minNotional": 200000.0, + "maxNotional": 500000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "4", + "initialLeverage": "5", + "notionalCap": "500000", + "notionalFloor": "200000", + "maintMarginRatio": "0.1", + "cum": "10650.0" + } + }, + { + "tier": 5.0, + "currency": "USDT", + "minNotional": 500000.0, + "maxNotional": 1000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 4.0, + "info": { + "bracket": "5", + "initialLeverage": "4", + "notionalCap": "1000000", + "notionalFloor": "500000", + "maintMarginRatio": "0.125", + "cum": "23150.0" + } + }, + { + "tier": 6.0, + "currency": "USDT", + "minNotional": 1000000.0, + "maxNotional": 3000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", "notionalCap": "3000000", "notionalFloor": "1000000", + "maintMarginRatio": "0.25", + "cum": "148150.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 3000000.0, + "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "7", + "initialLeverage": "1", + "notionalCap": "5000000", + "notionalFloor": "3000000", "maintMarginRatio": "0.5", - "cum": "386900.0" + "cum": "898150.0" } } ], @@ -19064,13 +20328,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, + "maxNotional": 300000.0, "maintenanceMarginRate": 0.05, "maxLeverage": 10.0, "info": { "bracket": "3", "initialLeverage": "10", - "notionalCap": "100000", + "notionalCap": "300000", "notionalFloor": "25000", "maintMarginRatio": "0.05", "cum": "700.0" @@ -19079,49 +20343,179 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, + "minNotional": 300000.0, + "maxNotional": 800000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "4", "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", + "notionalCap": "800000", + "notionalFloor": "300000", "maintMarginRatio": "0.1", - "cum": "5700.0" + "cum": "15700.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, + "minNotional": 800000.0, "maxNotional": 1000000.0, "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maxLeverage": 4.0, "info": { "bracket": "5", - "initialLeverage": "2", + "initialLeverage": "4", "notionalCap": "1000000", - "notionalFloor": "250000", + "notionalFloor": "800000", "maintMarginRatio": "0.125", - "cum": "11950.0" + "cum": "35700.0" } }, { "tier": 6.0, "currency": "USDT", "minNotional": 1000000.0, + "maxNotional": 3000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "3000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.25", + "cum": "160700.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 3000000.0, "maxNotional": 5000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "7", "initialLeverage": "1", "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalFloor": "3000000", "maintMarginRatio": "0.5", - "cum": "386950.0" + "cum": "910700.0" + } + } + ], + "STX/USDT:USDT": [ + { + "tier": 1.0, + "currency": "USDT", + "minNotional": 0.0, + "maxNotional": 5000.0, + "maintenanceMarginRate": 0.01, + "maxLeverage": 25.0, + "info": { + "bracket": "1", + "initialLeverage": "25", + "notionalCap": "5000", + "notionalFloor": "0", + "maintMarginRatio": "0.01", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "USDT", + "minNotional": 5000.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 20.0, + "info": { + "bracket": "2", + "initialLeverage": "20", + "notionalCap": "25000", + "notionalFloor": "5000", + "maintMarginRatio": "0.025", + "cum": "75.0" + } + }, + { + "tier": 3.0, + "currency": "USDT", + "minNotional": 25000.0, + "maxNotional": 400000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "3", + "initialLeverage": "10", + "notionalCap": "400000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "700.0" + } + }, + { + "tier": 4.0, + "currency": "USDT", + "minNotional": 400000.0, + "maxNotional": 1000000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "4", + "initialLeverage": "5", + "notionalCap": "1000000", + "notionalFloor": "400000", + "maintMarginRatio": "0.1", + "cum": "20700.0" + } + }, + { + "tier": 5.0, + "currency": "USDT", + "minNotional": 1000000.0, + "maxNotional": 2000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 4.0, + "info": { + "bracket": "5", + "initialLeverage": "4", + "notionalCap": "2000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.125", + "cum": "45700.0" + } + }, + { + "tier": 6.0, + "currency": "USDT", + "minNotional": 2000000.0, + "maxNotional": 6000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "6000000", + "notionalFloor": "2000000", + "maintMarginRatio": "0.25", + "cum": "295700.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 6000000.0, + "maxNotional": 10000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "7", + "initialLeverage": "1", + "notionalCap": "10000000", + "notionalFloor": "6000000", + "maintMarginRatio": "0.5", + "cum": "1795700.0" } } ], @@ -19941,6 +21335,120 @@ } } ], + "TRU/USDT:USDT": [ + { + "tier": 1.0, + "currency": "USDT", + "minNotional": 0.0, + "maxNotional": 5000.0, + "maintenanceMarginRate": 0.02, + "maxLeverage": 20.0, + "info": { + "bracket": "1", + "initialLeverage": "20", + "notionalCap": "5000", + "notionalFloor": "0", + "maintMarginRatio": "0.02", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "USDT", + "minNotional": 5000.0, + "maxNotional": 25000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 15.0, + "info": { + "bracket": "2", + "initialLeverage": "15", + "notionalCap": "25000", + "notionalFloor": "5000", + "maintMarginRatio": "0.025", + "cum": "25.0" + } + }, + { + "tier": 3.0, + "currency": "USDT", + "minNotional": 25000.0, + "maxNotional": 200000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "3", + "initialLeverage": "10", + "notionalCap": "200000", + "notionalFloor": "25000", + "maintMarginRatio": "0.05", + "cum": "650.0" + } + }, + { + "tier": 4.0, + "currency": "USDT", + "minNotional": 200000.0, + "maxNotional": 500000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "4", + "initialLeverage": "5", + "notionalCap": "500000", + "notionalFloor": "200000", + "maintMarginRatio": "0.1", + "cum": "10650.0" + } + }, + { + "tier": 5.0, + "currency": "USDT", + "minNotional": 500000.0, + "maxNotional": 1000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 4.0, + "info": { + "bracket": "5", + "initialLeverage": "4", + "notionalCap": "1000000", + "notionalFloor": "500000", + "maintMarginRatio": "0.125", + "cum": "23150.0" + } + }, + { + "tier": 6.0, + "currency": "USDT", + "minNotional": 1000000.0, + "maxNotional": 3000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "3000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.25", + "cum": "148150.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 3000000.0, + "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "7", + "initialLeverage": "1", + "notionalCap": "5000000", + "notionalFloor": "3000000", + "maintMarginRatio": "0.5", + "cum": "898150.0" + } + } + ], "TRX/BUSD:BUSD": [ { "tier": 1.0, @@ -20403,14 +21911,14 @@ "currency": "USDT", "minNotional": 0.0, "maxNotional": 5000.0, - "maintenanceMarginRate": 0.0065, - "maxLeverage": 25.0, + "maintenanceMarginRate": 0.006, + "maxLeverage": 50.0, "info": { "bracket": "1", - "initialLeverage": "25", + "initialLeverage": "50", "notionalCap": "5000", "notionalFloor": "0", - "maintMarginRatio": "0.0065", + "maintMarginRatio": "0.006", "cum": "0.0" } }, @@ -20418,96 +21926,242 @@ "tier": 2.0, "currency": "USDT", "minNotional": 5000.0, - "maxNotional": 10000.0, + "maxNotional": 50000.0, "maintenanceMarginRate": 0.01, - "maxLeverage": 20.0, + "maxLeverage": 25.0, "info": { "bracket": "2", - "initialLeverage": "20", - "notionalCap": "10000", + "initialLeverage": "25", + "notionalCap": "50000", "notionalFloor": "5000", "maintMarginRatio": "0.01", - "cum": "17.5" + "cum": "20.0" } }, { "tier": 3.0, "currency": "USDT", - "minNotional": 10000.0, - "maxNotional": 25000.0, + "minNotional": 50000.0, + "maxNotional": 400000.0, "maintenanceMarginRate": 0.025, - "maxLeverage": 10.0, + "maxLeverage": 20.0, "info": { "bracket": "3", - "initialLeverage": "10", - "notionalCap": "25000", - "notionalFloor": "10000", + "initialLeverage": "20", + "notionalCap": "400000", + "notionalFloor": "50000", "maintMarginRatio": "0.025", - "cum": "167.5" + "cum": "770.0" } }, { "tier": 4.0, "currency": "USDT", - "minNotional": 25000.0, - "maxNotional": 100000.0, + "minNotional": 400000.0, + "maxNotional": 800000.0, "maintenanceMarginRate": 0.05, - "maxLeverage": 8.0, + "maxLeverage": 10.0, "info": { "bracket": "4", - "initialLeverage": "8", - "notionalCap": "100000", - "notionalFloor": "25000", + "initialLeverage": "10", + "notionalCap": "800000", + "notionalFloor": "400000", "maintMarginRatio": "0.05", - "cum": "792.5" + "cum": "10770.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, + "minNotional": 800000.0, + "maxNotional": 2000000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "5", "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", + "notionalCap": "2000000", + "notionalFloor": "800000", "maintMarginRatio": "0.1", - "cum": "5792.5" + "cum": "50770.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 250000.0, + "minNotional": 2000000.0, "maxNotional": 5000000.0, "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maxLeverage": 4.0, "info": { "bracket": "6", - "initialLeverage": "2", + "initialLeverage": "4", "notionalCap": "5000000", - "notionalFloor": "250000", + "notionalFloor": "2000000", "maintMarginRatio": "0.125", - "cum": "12042.5" + "cum": "100770.0" } }, { "tier": 7.0, "currency": "USDT", "minNotional": 5000000.0, - "maxNotional": 8000000.0, + "maxNotional": 12000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "7", + "initialLeverage": "2", + "notionalCap": "12000000", + "notionalFloor": "5000000", + "maintMarginRatio": "0.25", + "cum": "725770.0" + } + }, + { + "tier": 8.0, + "currency": "USDT", + "minNotional": 12000000.0, + "maxNotional": 20000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "7", + "bracket": "8", "initialLeverage": "1", - "notionalCap": "8000000", - "notionalFloor": "5000000", + "notionalCap": "20000000", + "notionalFloor": "12000000", "maintMarginRatio": "0.5", - "cum": "1887042.5" + "cum": "3725770.0" + } + } + ], + "USDC/USDT:USDT": [ + { + "tier": 1.0, + "currency": "USDT", + "minNotional": 0.0, + "maxNotional": 5000.0, + "maintenanceMarginRate": 0.006, + "maxLeverage": 30.0, + "info": { + "bracket": "1", + "initialLeverage": "30", + "notionalCap": "5000", + "notionalFloor": "0", + "maintMarginRatio": "0.006", + "cum": "0.0" + } + }, + { + "tier": 2.0, + "currency": "USDT", + "minNotional": 5000.0, + "maxNotional": 50000.0, + "maintenanceMarginRate": 0.01, + "maxLeverage": 25.0, + "info": { + "bracket": "2", + "initialLeverage": "25", + "notionalCap": "50000", + "notionalFloor": "5000", + "maintMarginRatio": "0.01", + "cum": "20.0" + } + }, + { + "tier": 3.0, + "currency": "USDT", + "minNotional": 50000.0, + "maxNotional": 600000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 20.0, + "info": { + "bracket": "3", + "initialLeverage": "20", + "notionalCap": "600000", + "notionalFloor": "50000", + "maintMarginRatio": "0.025", + "cum": "770.0" + } + }, + { + "tier": 4.0, + "currency": "USDT", + "minNotional": 600000.0, + "maxNotional": 1200000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, + "info": { + "bracket": "4", + "initialLeverage": "10", + "notionalCap": "1200000", + "notionalFloor": "600000", + "maintMarginRatio": "0.05", + "cum": "15770.0" + } + }, + { + "tier": 5.0, + "currency": "USDT", + "minNotional": 1200000.0, + "maxNotional": 3200000.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, + "info": { + "bracket": "5", + "initialLeverage": "5", + "notionalCap": "3200000", + "notionalFloor": "1200000", + "maintMarginRatio": "0.1", + "cum": "75770.0" + } + }, + { + "tier": 6.0, + "currency": "USDT", + "minNotional": 3200000.0, + "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 4.0, + "info": { + "bracket": "6", + "initialLeverage": "4", + "notionalCap": "5000000", + "notionalFloor": "3200000", + "maintMarginRatio": "0.125", + "cum": "155770.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 5000000.0, + "maxNotional": 12000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "7", + "initialLeverage": "2", + "notionalCap": "12000000", + "notionalFloor": "5000000", + "maintMarginRatio": "0.25", + "cum": "780770.0" + } + }, + { + "tier": 8.0, + "currency": "USDT", + "minNotional": 12000000.0, + "maxNotional": 20000000.0, + "maintenanceMarginRate": 0.5, + "maxLeverage": 1.0, + "info": { + "bracket": "8", + "initialLeverage": "1", + "notionalCap": "20000000", + "notionalFloor": "12000000", + "maintMarginRatio": "0.5", + "cum": "3780770.0" } } ], @@ -20517,14 +22171,14 @@ "currency": "USDT", "minNotional": 0.0, "maxNotional": 5000.0, - "maintenanceMarginRate": 0.01, - "maxLeverage": 20.0, + "maintenanceMarginRate": 0.006, + "maxLeverage": 50.0, "info": { "bracket": "1", - "initialLeverage": "20", + "initialLeverage": "50", "notionalCap": "5000", "notionalFloor": "0", - "maintMarginRatio": "0.01", + "maintMarginRatio": "0.006", "cum": "0.0" } }, @@ -20533,63 +22187,63 @@ "currency": "USDT", "minNotional": 5000.0, "maxNotional": 25000.0, - "maintenanceMarginRate": 0.025, - "maxLeverage": 10.0, + "maintenanceMarginRate": 0.01, + "maxLeverage": 25.0, "info": { "bracket": "2", - "initialLeverage": "10", + "initialLeverage": "25", "notionalCap": "25000", "notionalFloor": "5000", - "maintMarginRatio": "0.025", - "cum": "75.0" + "maintMarginRatio": "0.01", + "cum": "20.0" } }, { "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, - "maintenanceMarginRate": 0.05, - "maxLeverage": 8.0, + "maxNotional": 200000.0, + "maintenanceMarginRate": 0.025, + "maxLeverage": 20.0, "info": { "bracket": "3", - "initialLeverage": "8", - "notionalCap": "100000", + "initialLeverage": "20", + "notionalCap": "200000", "notionalFloor": "25000", - "maintMarginRatio": "0.05", - "cum": "700.0" + "maintMarginRatio": "0.025", + "cum": "395.0" } }, { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, - "maintenanceMarginRate": 0.1, - "maxLeverage": 5.0, + "minNotional": 200000.0, + "maxNotional": 400000.0, + "maintenanceMarginRate": 0.05, + "maxLeverage": 10.0, "info": { "bracket": "4", - "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", - "maintMarginRatio": "0.1", - "cum": "5700.0" + "initialLeverage": "10", + "notionalCap": "400000", + "notionalFloor": "200000", + "maintMarginRatio": "0.05", + "cum": "5395.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, + "minNotional": 400000.0, "maxNotional": 1000000.0, - "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maintenanceMarginRate": 0.1, + "maxLeverage": 5.0, "info": { "bracket": "5", - "initialLeverage": "2", + "initialLeverage": "5", "notionalCap": "1000000", - "notionalFloor": "250000", - "maintMarginRatio": "0.125", - "cum": "11950.0" + "notionalFloor": "400000", + "maintMarginRatio": "0.1", + "cum": "25395.0" } }, { @@ -20597,15 +22251,47 @@ "currency": "USDT", "minNotional": 1000000.0, "maxNotional": 5000000.0, + "maintenanceMarginRate": 0.125, + "maxLeverage": 4.0, + "info": { + "bracket": "6", + "initialLeverage": "4", + "notionalCap": "5000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.125", + "cum": "50395.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 5000000.0, + "maxNotional": 6000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "7", + "initialLeverage": "2", + "notionalCap": "6000000", + "notionalFloor": "5000000", + "maintMarginRatio": "0.25", + "cum": "675395.0" + } + }, + { + "tier": 8.0, + "currency": "USDT", + "minNotional": 6000000.0, + "maxNotional": 10000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "8", "initialLeverage": "1", - "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalCap": "10000000", + "notionalFloor": "6000000", "maintMarginRatio": "0.5", - "cum": "386950.0" + "cum": "2175395.0" } } ], @@ -20714,10 +22400,10 @@ "minNotional": 0.0, "maxNotional": 5000.0, "maintenanceMarginRate": 0.02, - "maxLeverage": 15.0, + "maxLeverage": 25.0, "info": { "bracket": "1", - "initialLeverage": "15", + "initialLeverage": "25", "notionalCap": "5000", "notionalFloor": "0", "maintMarginRatio": "0.02", @@ -20730,10 +22416,10 @@ "minNotional": 5000.0, "maxNotional": 25000.0, "maintenanceMarginRate": 0.025, - "maxLeverage": 10.0, + "maxLeverage": 20.0, "info": { "bracket": "2", - "initialLeverage": "10", + "initialLeverage": "20", "notionalCap": "25000", "notionalFloor": "5000", "maintMarginRatio": "0.025", @@ -20744,13 +22430,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 120000.0, + "maxNotional": 200000.0, "maintenanceMarginRate": 0.05, - "maxLeverage": 8.0, + "maxLeverage": 10.0, "info": { "bracket": "3", - "initialLeverage": "8", - "notionalCap": "120000", + "initialLeverage": "10", + "notionalCap": "200000", "notionalFloor": "25000", "maintMarginRatio": "0.05", "cum": "650.0" @@ -20759,33 +22445,33 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 120000.0, - "maxNotional": 300000.0, + "minNotional": 200000.0, + "maxNotional": 500000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "4", "initialLeverage": "5", - "notionalCap": "300000", - "notionalFloor": "120000", + "notionalCap": "500000", + "notionalFloor": "200000", "maintMarginRatio": "0.1", - "cum": "6650.0" + "cum": "10650.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 300000.0, + "minNotional": 500000.0, "maxNotional": 1000000.0, "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maxLeverage": 4.0, "info": { "bracket": "5", - "initialLeverage": "2", + "initialLeverage": "4", "notionalCap": "1000000", - "notionalFloor": "300000", + "notionalFloor": "500000", "maintMarginRatio": "0.125", - "cum": "14150.0" + "cum": "23150.0" } }, { @@ -20793,15 +22479,31 @@ "currency": "USDT", "minNotional": 1000000.0, "maxNotional": 3000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "3000000", + "notionalFloor": "1000000", + "maintMarginRatio": "0.25", + "cum": "148150.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 3000000.0, + "maxNotional": 5000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "7", "initialLeverage": "1", - "notionalCap": "3000000", - "notionalFloor": "1000000", + "notionalCap": "5000000", + "notionalFloor": "3000000", "maintMarginRatio": "0.5", - "cum": "389150.0" + "cum": "898150.0" } } ], @@ -20910,10 +22612,10 @@ "minNotional": 0.0, "maxNotional": 5000.0, "maintenanceMarginRate": 0.02, - "maxLeverage": 20.0, + "maxLeverage": 25.0, "info": { "bracket": "1", - "initialLeverage": "20", + "initialLeverage": "25", "notionalCap": "5000", "notionalFloor": "0", "maintMarginRatio": "0.02", @@ -20926,10 +22628,10 @@ "minNotional": 5000.0, "maxNotional": 25000.0, "maintenanceMarginRate": 0.025, - "maxLeverage": 10.0, + "maxLeverage": 20.0, "info": { "bracket": "2", - "initialLeverage": "10", + "initialLeverage": "20", "notionalCap": "25000", "notionalFloor": "5000", "maintMarginRatio": "0.025", @@ -20940,13 +22642,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, + "maxNotional": 400000.0, "maintenanceMarginRate": 0.05, - "maxLeverage": 8.0, + "maxLeverage": 10.0, "info": { "bracket": "3", - "initialLeverage": "8", - "notionalCap": "100000", + "initialLeverage": "10", + "notionalCap": "400000", "notionalFloor": "25000", "maintMarginRatio": "0.05", "cum": "650.0" @@ -20955,49 +22657,65 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, + "minNotional": 400000.0, + "maxNotional": 1000000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "4", "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", + "notionalCap": "1000000", + "notionalFloor": "400000", "maintMarginRatio": "0.1", - "cum": "5650.0" + "cum": "20650.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, - "maxNotional": 1000000.0, + "minNotional": 1000000.0, + "maxNotional": 2000000.0, "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maxLeverage": 4.0, "info": { "bracket": "5", - "initialLeverage": "2", - "notionalCap": "1000000", - "notionalFloor": "250000", + "initialLeverage": "4", + "notionalCap": "2000000", + "notionalFloor": "1000000", "maintMarginRatio": "0.125", - "cum": "11900.0" + "cum": "45650.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 1000000.0, - "maxNotional": 3000000.0, + "minNotional": 2000000.0, + "maxNotional": 6000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "6000000", + "notionalFloor": "2000000", + "maintMarginRatio": "0.25", + "cum": "295650.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 6000000.0, + "maxNotional": 10000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "7", "initialLeverage": "1", - "notionalCap": "3000000", - "notionalFloor": "1000000", + "notionalCap": "10000000", + "notionalFloor": "6000000", "maintMarginRatio": "0.5", - "cum": "386900.0" + "cum": "1795650.0" } } ], @@ -21640,13 +23358,13 @@ "tier": 3.0, "currency": "USDT", "minNotional": 25000.0, - "maxNotional": 100000.0, + "maxNotional": 400000.0, "maintenanceMarginRate": 0.05, "maxLeverage": 10.0, "info": { "bracket": "3", "initialLeverage": "10", - "notionalCap": "100000", + "notionalCap": "400000", "notionalFloor": "25000", "maintMarginRatio": "0.05", "cum": "700.0" @@ -21655,49 +23373,65 @@ { "tier": 4.0, "currency": "USDT", - "minNotional": 100000.0, - "maxNotional": 250000.0, + "minNotional": 400000.0, + "maxNotional": 1000000.0, "maintenanceMarginRate": 0.1, "maxLeverage": 5.0, "info": { "bracket": "4", "initialLeverage": "5", - "notionalCap": "250000", - "notionalFloor": "100000", + "notionalCap": "1000000", + "notionalFloor": "400000", "maintMarginRatio": "0.1", - "cum": "5700.0" + "cum": "20700.0" } }, { "tier": 5.0, "currency": "USDT", - "minNotional": 250000.0, - "maxNotional": 1000000.0, + "minNotional": 1000000.0, + "maxNotional": 2000000.0, "maintenanceMarginRate": 0.125, - "maxLeverage": 2.0, + "maxLeverage": 4.0, "info": { "bracket": "5", - "initialLeverage": "2", - "notionalCap": "1000000", - "notionalFloor": "250000", + "initialLeverage": "4", + "notionalCap": "2000000", + "notionalFloor": "1000000", "maintMarginRatio": "0.125", - "cum": "11950.0" + "cum": "45700.0" } }, { "tier": 6.0, "currency": "USDT", - "minNotional": 1000000.0, - "maxNotional": 5000000.0, + "minNotional": 2000000.0, + "maxNotional": 6000000.0, + "maintenanceMarginRate": 0.25, + "maxLeverage": 2.0, + "info": { + "bracket": "6", + "initialLeverage": "2", + "notionalCap": "6000000", + "notionalFloor": "2000000", + "maintMarginRatio": "0.25", + "cum": "295700.0" + } + }, + { + "tier": 7.0, + "currency": "USDT", + "minNotional": 6000000.0, + "maxNotional": 10000000.0, "maintenanceMarginRate": 0.5, "maxLeverage": 1.0, "info": { - "bracket": "6", + "bracket": "7", "initialLeverage": "1", - "notionalCap": "5000000", - "notionalFloor": "1000000", + "notionalCap": "10000000", + "notionalFloor": "6000000", "maintMarginRatio": "0.5", - "cum": "386950.0" + "cum": "1795700.0" } } ], From ad5afd30478a22d95818c678698fd175ff7a44a5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 13 Mar 2023 08:08:57 +0000 Subject: [PATCH 142/229] Bump uvicorn from 0.20.0 to 0.21.0 Bumps [uvicorn](https://github.com/encode/uvicorn) from 0.20.0 to 0.21.0. - [Release notes](https://github.com/encode/uvicorn/releases) - [Changelog](https://github.com/encode/uvicorn/blob/master/CHANGELOG.md) - [Commits](https://github.com/encode/uvicorn/compare/0.20.0...0.21.0) --- updated-dependencies: - dependency-name: uvicorn dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index f5a8f068c..868fc9699 100644 --- a/requirements.txt +++ b/requirements.txt @@ -36,7 +36,7 @@ sdnotify==0.3.2 # API Server fastapi==0.94.0 pydantic==1.10.6 -uvicorn==0.20.0 +uvicorn==0.21.0 pyjwt==2.6.0 aiofiles==23.1.0 psutil==5.9.4 From f3a1177badd09e84c81e0f220b77c36082a656d8 Mon Sep 17 00:00:00 2001 From: initrv Date: Mon, 13 Mar 2023 17:53:35 +0300 Subject: [PATCH 143/229] bring inc back --- freqtrade/freqai/RL/BaseEnvironment.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/freqtrade/freqai/RL/BaseEnvironment.py b/freqtrade/freqai/RL/BaseEnvironment.py index a9a9a613c..7ac77361c 100644 --- a/freqtrade/freqai/RL/BaseEnvironment.py +++ b/freqtrade/freqai/RL/BaseEnvironment.py @@ -138,7 +138,7 @@ class BaseEnvironment(gym.Env): return [seed] def tensorboard_log(self, metric: str, value: Optional[Union[int, float]] = None, - category: str = "custom"): + inc: Optional[bool] = None, category: str = "custom"): """ Function builds the tensorboard_metrics dictionary to be parsed by the TensorboardCallback. This @@ -155,6 +155,7 @@ class BaseEnvironment(gym.Env): :param metric: metric to be tracked and incremented :param value: `metric` value + :param inc: (deprecated) sets whether the `value` is incremented or not :param category: `metric` category """ increment = True if value is None else False From d723979c4288c35f230734cf03d7c39fb20c539b Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 13 Mar 2023 19:21:53 +0100 Subject: [PATCH 144/229] Move total_trades to explicit variable --- freqtrade/rpc/rpc.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index c68ed2d48..727fc5a37 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -388,12 +388,13 @@ class RPC: Trade.close_date.desc()) output = [trade.to_json() for trade in trades] + total_trades = Trade.get_trades([Trade.is_open.is_(False)]).count() return { "trades": output, "trades_count": len(output), "offset": offset, - "total_trades": Trade.get_trades([Trade.is_open.is_(False)]).count(), + "total_trades": total_trades, } def _rpc_stats(self) -> Dict[str, Any]: From 3d31eca3653c7944eefa04d9284e578d1753498b Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 13 Mar 2023 19:40:48 +0100 Subject: [PATCH 145/229] Update Exception to contain more info part of #8300 --- freqtrade/exchange/exchange.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/freqtrade/exchange/exchange.py b/freqtrade/exchange/exchange.py index c0e07c6d7..24fc8daa1 100644 --- a/freqtrade/exchange/exchange.py +++ b/freqtrade/exchange/exchange.py @@ -1138,7 +1138,10 @@ class Exchange: # Ensure rate is less than stop price if bad_stop_price: raise OperationalException( - 'In stoploss limit order, stop price should be more than limit price') + "In stoploss limit order, stop price should be more than limit price. " + f"Stop price: {stop_price}, Limit price: {limit_rate}, " + f"Limit Price pct: {limit_price_pct}" + ) return limit_rate def _get_stop_params(self, side: BuySell, ordertype: str, stop_price: float) -> Dict: From cf70deaf8d7faed50a8bfbf7c0ca0ff605db4979 Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 13 Mar 2023 19:41:39 +0100 Subject: [PATCH 146/229] Disallow negative liquidation prices part of #8300 --- freqtrade/exchange/exchange.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/freqtrade/exchange/exchange.py b/freqtrade/exchange/exchange.py index 24fc8daa1..0e0c05cb1 100644 --- a/freqtrade/exchange/exchange.py +++ b/freqtrade/exchange/exchange.py @@ -2785,7 +2785,7 @@ class Exchange: if is_short else isolated_liq + buffer_amount ) - return isolated_liq + return max(isolated_liq, 0.0) else: return None From 8fd13933c30d53a02e04dfb88fca89b65bba6e78 Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 13 Mar 2023 19:50:19 +0100 Subject: [PATCH 147/229] Improve variable naming --- freqtrade/exchange/exchange.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/freqtrade/exchange/exchange.py b/freqtrade/exchange/exchange.py index 0e0c05cb1..e2a36d3a3 100644 --- a/freqtrade/exchange/exchange.py +++ b/freqtrade/exchange/exchange.py @@ -2758,10 +2758,10 @@ class Exchange: raise OperationalException( f"{self.name} does not support {self.margin_mode} {self.trading_mode}") - isolated_liq = None + liquidation_price = None if self._config['dry_run'] or not self.exchange_has("fetchPositions"): - isolated_liq = self.dry_run_liquidation_price( + liquidation_price = self.dry_run_liquidation_price( pair=pair, open_rate=open_rate, is_short=is_short, @@ -2776,16 +2776,16 @@ class Exchange: positions = self.fetch_positions(pair) if len(positions) > 0: pos = positions[0] - isolated_liq = pos['liquidationPrice'] + liquidation_price = pos['liquidationPrice'] - if isolated_liq is not None: - buffer_amount = abs(open_rate - isolated_liq) * self.liquidation_buffer - isolated_liq = ( - isolated_liq - buffer_amount + if liquidation_price is not None: + buffer_amount = abs(open_rate - liquidation_price) * self.liquidation_buffer + liquidation_price_buffer = ( + liquidation_price - buffer_amount if is_short else - isolated_liq + buffer_amount + liquidation_price + buffer_amount ) - return max(isolated_liq, 0.0) + return max(liquidation_price_buffer, 0.0) else: return None From 487469680f1d4120fe1d40cb9d870047425f0559 Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 13 Mar 2023 20:13:12 +0100 Subject: [PATCH 148/229] Use correct exception type for ccxt.InvalidOrder --- freqtrade/exchange/exchange.py | 2 +- tests/exchange/test_exchange.py | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/freqtrade/exchange/exchange.py b/freqtrade/exchange/exchange.py index e2a36d3a3..489dc1b68 100644 --- a/freqtrade/exchange/exchange.py +++ b/freqtrade/exchange/exchange.py @@ -1087,7 +1087,7 @@ class Exchange: f'Tried to {side} amount {amount} at rate {rate}.' f'Message: {e}') from e except ccxt.InvalidOrder as e: - raise ExchangeError( + raise InvalidOrderException( f'Could not create {ordertype} {side} order on market {pair}. ' f'Tried to {side} amount {amount} at rate {rate}. ' f'Message: {e}') from e diff --git a/tests/exchange/test_exchange.py b/tests/exchange/test_exchange.py index 940319a45..d7f6a8b90 100644 --- a/tests/exchange/test_exchange.py +++ b/tests/exchange/test_exchange.py @@ -12,8 +12,8 @@ from pandas import DataFrame from freqtrade.enums import CandleType, MarginMode, TradingMode from freqtrade.exceptions import (DDosProtection, DependencyException, ExchangeError, - InvalidOrderException, OperationalException, PricingError, - TemporaryError) + InsufficientFundsError, InvalidOrderException, + OperationalException, PricingError, TemporaryError) from freqtrade.exchange import (Binance, Bittrex, Exchange, Kraken, amount_to_precision, date_minus_candles, market_is_active, price_to_precision, timeframe_to_minutes, timeframe_to_msecs, timeframe_to_next_date, @@ -1599,13 +1599,13 @@ def test_sell_prod(default_conf, mocker, exchange_name): assert api_mock.create_order.call_args[0][4] == 200 # test exception handling - with pytest.raises(DependencyException): + with pytest.raises(InsufficientFundsError): api_mock.create_order = MagicMock(side_effect=ccxt.InsufficientFunds("0 balance")) exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) exchange.create_order(pair='ETH/BTC', ordertype=order_type, side="sell", amount=1, rate=200, leverage=1.0) - with pytest.raises(DependencyException): + with pytest.raises(InvalidOrderException): api_mock.create_order = MagicMock(side_effect=ccxt.InvalidOrder("Order not found")) exchange = get_patched_exchange(mocker, default_conf, api_mock, id=exchange_name) exchange.create_order(pair='ETH/BTC', ordertype='limit', side="sell", amount=1, rate=200, From b23cea6e59ae252dd39222544e739bc953e3ac3d Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 13 Mar 2023 20:16:12 +0100 Subject: [PATCH 149/229] Bump ruff to 0.0.255 --- .pre-commit-config.yaml | 2 +- requirements-dev.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 2d1fb20fc..bc2e0bc0d 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -30,7 +30,7 @@ repos: - repo: https://github.com/charliermarsh/ruff-pre-commit # Ruff version. - rev: 'v0.0.251' + rev: 'v0.0.255' hooks: - id: ruff diff --git a/requirements-dev.txt b/requirements-dev.txt index 44c1a69fc..6d076777f 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -7,7 +7,7 @@ -r docs/requirements-docs.txt coveralls==3.3.1 -ruff==0.0.254 +ruff==0.0.255 mypy==1.1.1 pre-commit==3.1.1 pytest==7.2.2 From 5c280d5649b431b8ff366c14acca8db6d7b45c32 Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 13 Mar 2023 20:28:13 +0100 Subject: [PATCH 150/229] Improve emergency_exit handling --- freqtrade/freqtradebot.py | 20 +++++++++++--------- tests/test_freqtradebot.py | 6 +++--- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index 3924b111f..ec61f45b1 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -1122,8 +1122,7 @@ class FreqtradeBot(LoggingMixin): trade.stoploss_order_id = None logger.error(f'Unable to place a stoploss order on exchange. {e}') logger.warning('Exiting the trade forcefully') - self.execute_trade_exit(trade, stop_price, exit_check=ExitCheckTuple( - exit_type=ExitType.EMERGENCY_EXIT)) + self.emergency_exit(trade, stop_price) except ExchangeError: trade.stoploss_order_id = None @@ -1281,13 +1280,16 @@ class FreqtradeBot(LoggingMixin): if canceled and max_timeouts > 0 and canceled_count >= max_timeouts: logger.warning(f'Emergency exiting trade {trade}, as the exit order ' f'timed out {max_timeouts} times.') - try: - self.execute_trade_exit( - trade, order['price'], - exit_check=ExitCheckTuple(exit_type=ExitType.EMERGENCY_EXIT)) - except DependencyException as exception: - logger.warning( - f'Unable to emergency sell trade {trade.pair}: {exception}') + self.emergency_exit(trade, order['price']) + + def emergency_exit(self, trade: Trade, price: float) -> None: + try: + self.execute_trade_exit( + trade, price, + exit_check=ExitCheckTuple(exit_type=ExitType.EMERGENCY_EXIT)) + except DependencyException as exception: + logger.warning( + f'Unable to emergency exit trade {trade.pair}: {exception}') def replace_order(self, order: Dict, order_obj: Optional[Order], trade: Trade) -> None: """ diff --git a/tests/test_freqtradebot.py b/tests/test_freqtradebot.py index 06832589c..349655243 100644 --- a/tests/test_freqtradebot.py +++ b/tests/test_freqtradebot.py @@ -2724,21 +2724,21 @@ def test_manage_open_orders_exit_usercustom( assert freqtrade.strategy.check_exit_timeout.call_count == 1 assert freqtrade.strategy.check_entry_timeout.call_count == 0 - # 2nd canceled trade - Fail execute sell + # 2nd canceled trade - Fail execute exit caplog.clear() open_trade_usdt.open_order_id = limit_sell_order_old['id'] mocker.patch('freqtrade.persistence.Trade.get_exit_order_count', return_value=1) mocker.patch('freqtrade.freqtradebot.FreqtradeBot.execute_trade_exit', side_effect=DependencyException) freqtrade.manage_open_orders() - assert log_has_re('Unable to emergency sell .*', caplog) + assert log_has_re('Unable to emergency exit .*', caplog) et_mock = mocker.patch('freqtrade.freqtradebot.FreqtradeBot.execute_trade_exit') caplog.clear() # 2nd canceled trade ... open_trade_usdt.open_order_id = limit_sell_order_old['id'] - # If cancelling fails - no emergency sell! + # If cancelling fails - no emergency exit! with patch('freqtrade.freqtradebot.FreqtradeBot.handle_cancel_exit', return_value=False): freqtrade.manage_open_orders() assert et_mock.call_count == 0 From 8f29312c9e6f6637628965c28dcb9409f562c29e Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 14 Mar 2023 08:14:01 +0100 Subject: [PATCH 151/229] Minimum re-entry stake should not include stoploss --- freqtrade/freqtradebot.py | 14 +++++++++++--- freqtrade/optimize/backtesting.py | 2 +- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index ec61f45b1..dfac11347 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -586,7 +586,7 @@ class FreqtradeBot(LoggingMixin): min_entry_stake = self.exchange.get_min_pair_stake_amount(trade.pair, current_entry_rate, - self.strategy.stoploss) + 0.0) min_exit_stake = self.exchange.get_min_pair_stake_amount(trade.pair, current_exit_rate, self.strategy.stoploss) @@ -700,7 +700,8 @@ class FreqtradeBot(LoggingMixin): pos_adjust = trade is not None enter_limit_requested, stake_amount, leverage = self.get_valid_enter_price_and_stake( - pair, price, stake_amount, trade_side, enter_tag, trade, order_adjust, leverage_) + pair, price, stake_amount, trade_side, enter_tag, trade, order_adjust, leverage_, + pos_adjust) if not stake_amount: return False @@ -860,7 +861,12 @@ class FreqtradeBot(LoggingMixin): trade: Optional[Trade], order_adjust: bool, leverage_: Optional[float], + pos_adjust: bool, ) -> Tuple[float, float, float]: + """ + Validate and eventually adjust (within limits) limit, amount and leverage + :return: Tuple with (price, amount, leverage) + """ if price: enter_limit_requested = price @@ -906,7 +912,9 @@ class FreqtradeBot(LoggingMixin): # We do however also need min-stake to determine leverage, therefore this is ignored as # edge-case for now. min_stake_amount = self.exchange.get_min_pair_stake_amount( - pair, enter_limit_requested, self.strategy.stoploss, leverage) + pair, enter_limit_requested, + self.strategy.stoploss if not pos_adjust else 0.0, + leverage) max_stake_amount = self.exchange.get_max_pair_stake_amount( pair, enter_limit_requested, leverage) diff --git a/freqtrade/optimize/backtesting.py b/freqtrade/optimize/backtesting.py index 83b65d24b..5e1e9b48a 100644 --- a/freqtrade/optimize/backtesting.py +++ b/freqtrade/optimize/backtesting.py @@ -749,7 +749,7 @@ class Backtesting: leverage = min(max(leverage, 1.0), max_leverage) min_stake_amount = self.exchange.get_min_pair_stake_amount( - pair, propose_rate, -0.05, leverage=leverage) or 0 + pair, propose_rate, -0.05 if not pos_adjust else 0.0, leverage=leverage) or 0 max_stake_amount = self.exchange.get_max_pair_stake_amount( pair, propose_rate, leverage=leverage) stake_available = self.wallets.get_available_stake_amount() From 7e08e3a59a964801f02f083d71a76b17e3a6dcc6 Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 15 Mar 2023 07:22:07 +0100 Subject: [PATCH 152/229] Update example to use get_trades_proxy --- docs/strategy-customization.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/docs/strategy-customization.md b/docs/strategy-customization.md index 8ab0b1464..8b6654c6c 100644 --- a/docs/strategy-customization.md +++ b/docs/strategy-customization.md @@ -1040,11 +1040,10 @@ from datetime import timedelta, datetime, timezone # Within populate indicators (or populate_buy): if self.config['runmode'].value in ('live', 'dry_run'): - # fetch closed trades for the last 2 days - trades = Trade.get_trades([Trade.pair == metadata['pair'], - Trade.open_date > datetime.utcnow() - timedelta(days=2), - Trade.is_open.is_(False), - ]).all() + # fetch closed trades for the last 2 days + trades = Trade.get_trades_proxy( + pair=metadata['pair'], is_open=False, + open_date=datetime.now(timezone.utc) - timedelta(days=2)) # Analyze the conditions you'd like to lock the pair .... will probably be different for every strategy sumprofit = sum(trade.close_profit for trade in trades) if sumprofit < 0: From 95ff59a21c910d13f463ab6c3fe57bff0eb08695 Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 15 Mar 2023 07:23:54 +0100 Subject: [PATCH 153/229] Improve documentation for get_trades_proxy --- freqtrade/persistence/trade_model.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 8e8a414c8..19d71aa7b 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -1088,6 +1088,11 @@ class LocalTrade(): In live mode, converts the filter to a database query and returns all rows In Backtest mode, uses filters on Trade.trades to get the result. + :param pair: Filter by pair + :param is_open: Filter by open/closed status + :param open_date: Filter by open_date (filters via trade.open_date > input) + :param close_date: Filter by close_date (filters via trade.close_date > input) + Will implicitly only return closed trades. :return: unsorted List[Trade] """ From 47ab285252996cf7eabd109eba09973272917b26 Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 15 Mar 2023 20:49:35 +0100 Subject: [PATCH 154/229] Minor test fix --- tests/rpc/test_rpc_telegram.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/rpc/test_rpc_telegram.py b/tests/rpc/test_rpc_telegram.py index 1dc255b3e..59b6df489 100644 --- a/tests/rpc/test_rpc_telegram.py +++ b/tests/rpc/test_rpc_telegram.py @@ -302,8 +302,7 @@ def test_telegram_status_closed_trade(default_conf, update, mocker, fee) -> None telegram, _, msg_mock = get_telegram_testobject(mocker, default_conf) create_mock_trades(fee) - trades = Trade.get_trades([Trade.is_open.is_(False)]) - trade = trades[0] + trade = Trade.get_trades([Trade.is_open.is_(False)]).first() context = MagicMock() context.args = [str(trade.id)] telegram._status(update=update, context=context) From b469addffb09945f50d36eed0a9273b242d9626c Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 15 Mar 2023 21:00:30 +0100 Subject: [PATCH 155/229] remove usage of .query from regular models --- freqtrade/persistence/trade_model.py | 142 +++++++++++++++----------- freqtrade/rpc/rpc.py | 39 ++++--- tests/persistence/test_persistence.py | 8 +- 3 files changed, 114 insertions(+), 75 deletions(-) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 19d71aa7b..a2bbd1ee1 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -7,7 +7,8 @@ from datetime import datetime, timedelta, timezone from math import isclose from typing import Any, ClassVar, Dict, List, Optional, cast -from sqlalchemy import Enum, Float, ForeignKey, Integer, String, UniqueConstraint, desc, func +from sqlalchemy import (Enum, Float, ForeignKey, Integer, Result, Select, String, UniqueConstraint, + desc, func, select) from sqlalchemy.orm import (Mapped, Query, QueryPropertyDescriptor, lazyload, mapped_column, relationship) @@ -1153,7 +1154,9 @@ class LocalTrade(): get open trade count """ if Trade.use_db: - return Trade.query.filter(Trade.is_open.is_(True)).count() + return Trade._session.scalar( + select(func.count(Trade.id)).filter(Trade.is_open.is_(True)) + ) else: return LocalTrade.bt_open_open_trade_count @@ -1287,18 +1290,18 @@ class Trade(ModelBase, LocalTrade): def delete(self) -> None: for order in self.orders: - Order.query.session.delete(order) + Order._session.delete(order) - Trade.query.session.delete(self) + Trade._session.delete(self) Trade.commit() @staticmethod def commit(): - Trade.query.session.commit() + Trade._session.commit() @staticmethod def rollback(): - Trade.query.session.rollback() + Trade._session.rollback() @staticmethod def get_trades_proxy(*, pair: Optional[str] = None, is_open: Optional[bool] = None, @@ -1332,7 +1335,7 @@ class Trade(ModelBase, LocalTrade): ) @staticmethod - def get_trades(trade_filter=None, include_orders: bool = True) -> Query['Trade']: + def get_trades_query(trade_filter=None, include_orders: bool = True) -> Select['Trade']: """ Helper function to query Trades using filters. NOTE: Not supported in Backtesting. @@ -1347,15 +1350,28 @@ class Trade(ModelBase, LocalTrade): if trade_filter is not None: if not isinstance(trade_filter, list): trade_filter = [trade_filter] - this_query = Trade.query.filter(*trade_filter) + this_query = select(Trade).filter(*trade_filter) else: - this_query = Trade.query + this_query = select(Trade) if not include_orders: # Don't load order relations # Consider using noload or raiseload instead of lazyload this_query = this_query.options(lazyload(Trade.orders)) return this_query + @staticmethod + def get_trades(trade_filter=None, include_orders: bool = True) -> Query['Trade']: + """ + Helper function to query Trades using filters. + NOTE: Not supported in Backtesting. + :param trade_filter: Optional filter to apply to trades + Can be either a Filter object, or a List of filters + e.g. `(trade_filter=[Trade.id == trade_id, Trade.is_open.is_(True),])` + e.g. `(trade_filter=Trade.id == trade_id)` + :return: unsorted query object + """ + return Trade._session.execute(Trade.get_trades_query(trade_filter, include_orders)) + @staticmethod def get_open_order_trades() -> List['Trade']: """ @@ -1392,8 +1408,9 @@ class Trade(ModelBase, LocalTrade): Retrieves total realized profit """ if Trade.use_db: - total_profit = Trade.query.with_entities( - func.sum(Trade.close_profit_abs)).filter(Trade.is_open.is_(False)).scalar() + total_profit = Trade._session.scalar( + select(func.sum(Trade.close_profit_abs)).filter(Trade.is_open.is_(False)) + ) else: total_profit = sum( t.close_profit_abs for t in LocalTrade.get_trades_proxy(is_open=False)) @@ -1406,8 +1423,9 @@ class Trade(ModelBase, LocalTrade): in stake currency """ if Trade.use_db: - total_open_stake_amount = Trade.query.with_entities( - func.sum(Trade.stake_amount)).filter(Trade.is_open.is_(True)).scalar() + total_open_stake_amount = Trade._session.scalar( + select(func.sum(Trade.stake_amount)).filter(Trade.is_open.is_(True)) + ) else: total_open_stake_amount = sum( t.stake_amount for t in LocalTrade.get_trades_proxy(is_open=True)) @@ -1423,15 +1441,18 @@ class Trade(ModelBase, LocalTrade): if minutes: start_date = datetime.now(timezone.utc) - timedelta(minutes=minutes) filters.append(Trade.close_date >= start_date) - pair_rates = Trade.query.with_entities( - Trade.pair, - func.sum(Trade.close_profit).label('profit_sum'), - func.sum(Trade.close_profit_abs).label('profit_sum_abs'), - func.count(Trade.pair).label('count') - ).filter(*filters)\ - .group_by(Trade.pair) \ - .order_by(desc('profit_sum_abs')) \ - .all() + + pair_rates = Trade._session.execute( + select( + Trade.pair, + func.sum(Trade.close_profit).label('profit_sum'), + func.sum(Trade.close_profit_abs).label('profit_sum_abs'), + func.count(Trade.pair).label('count') + ).filter(*filters) + .group_by(Trade.pair) + .order_by(desc('profit_sum_abs')) + ).all() + return [ { 'pair': pair, @@ -1456,15 +1477,16 @@ class Trade(ModelBase, LocalTrade): if (pair is not None): filters.append(Trade.pair == pair) - enter_tag_perf = Trade.query.with_entities( - Trade.enter_tag, - func.sum(Trade.close_profit).label('profit_sum'), - func.sum(Trade.close_profit_abs).label('profit_sum_abs'), - func.count(Trade.pair).label('count') - ).filter(*filters)\ - .group_by(Trade.enter_tag) \ - .order_by(desc('profit_sum_abs')) \ - .all() + enter_tag_perf = Trade._session.execute( + select( + Trade.enter_tag, + func.sum(Trade.close_profit).label('profit_sum'), + func.sum(Trade.close_profit_abs).label('profit_sum_abs'), + func.count(Trade.pair).label('count') + ).filter(*filters) + .group_by(Trade.enter_tag) + .order_by(desc('profit_sum_abs')) + ).all() return [ { @@ -1488,16 +1510,16 @@ class Trade(ModelBase, LocalTrade): filters: List = [Trade.is_open.is_(False)] if (pair is not None): filters.append(Trade.pair == pair) - - sell_tag_perf = Trade.query.with_entities( - Trade.exit_reason, - func.sum(Trade.close_profit).label('profit_sum'), - func.sum(Trade.close_profit_abs).label('profit_sum_abs'), - func.count(Trade.pair).label('count') - ).filter(*filters)\ - .group_by(Trade.exit_reason) \ - .order_by(desc('profit_sum_abs')) \ - .all() + sell_tag_perf = Trade._session.execute( + select( + Trade.exit_reason, + func.sum(Trade.close_profit).label('profit_sum'), + func.sum(Trade.close_profit_abs).label('profit_sum_abs'), + func.count(Trade.pair).label('count') + ).filter(*filters) + .group_by(Trade.exit_reason) + .order_by(desc('profit_sum_abs')) + ).all() return [ { @@ -1521,18 +1543,18 @@ class Trade(ModelBase, LocalTrade): filters: List = [Trade.is_open.is_(False)] if (pair is not None): filters.append(Trade.pair == pair) - - mix_tag_perf = Trade.query.with_entities( - Trade.id, - Trade.enter_tag, - Trade.exit_reason, - func.sum(Trade.close_profit).label('profit_sum'), - func.sum(Trade.close_profit_abs).label('profit_sum_abs'), - func.count(Trade.pair).label('count') - ).filter(*filters)\ - .group_by(Trade.id) \ - .order_by(desc('profit_sum_abs')) \ - .all() + mix_tag_perf = Trade._session.execute( + select( + Trade.id, + Trade.enter_tag, + Trade.exit_reason, + func.sum(Trade.close_profit).label('profit_sum'), + func.sum(Trade.close_profit_abs).label('profit_sum_abs'), + func.count(Trade.pair).label('count') + ).filter(*filters) + .group_by(Trade.id) + .order_by(desc('profit_sum_abs')) + ).all() return_list: List[Dict] = [] for id, enter_tag, exit_reason, profit, profit_abs, count in mix_tag_perf: @@ -1568,11 +1590,15 @@ class Trade(ModelBase, LocalTrade): NOTE: Not supported in Backtesting. :returns: Tuple containing (pair, profit_sum) """ - best_pair = Trade.query.with_entities( - Trade.pair, func.sum(Trade.close_profit).label('profit_sum') - ).filter(Trade.is_open.is_(False) & (Trade.close_date >= start_date)) \ - .group_by(Trade.pair) \ - .order_by(desc('profit_sum')).first() + best_pair = Trade._session.execute( + select( + Trade.pair, + func.sum(Trade.close_profit).label('profit_sum') + ).filter(Trade.is_open.is_(False) & (Trade.close_date >= start_date)) + .group_by(Trade.pair) + .order_by(desc('profit_sum')) + ).first() + return best_pair @staticmethod diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 727fc5a37..db2b35049 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -5,7 +5,7 @@ import logging from abc import abstractmethod from datetime import date, datetime, timedelta, timezone from math import isnan -from typing import Any, Dict, Generator, List, Optional, Tuple, Union +from typing import Any, Dict, Generator, List, Optional, Sequence, Tuple, Union import arrow import psutil @@ -13,6 +13,7 @@ from dateutil.relativedelta import relativedelta from dateutil.tz import tzlocal from numpy import NAN, inf, int64, mean from pandas import DataFrame, NaT +from sqlalchemy import func, select from freqtrade import __version__ from freqtrade.configuration.timerange import TimeRange @@ -339,11 +340,18 @@ class RPC: for day in range(0, timescale): profitday = start_date - time_offset(day) # Only query for necessary columns for performance reasons. - trades = Trade.query.session.query(Trade.close_profit_abs).filter( - Trade.is_open.is_(False), - Trade.close_date >= profitday, - Trade.close_date < (profitday + time_offset(1)) - ).order_by(Trade.close_date).all() + trades = Trade._session.execute( + select(Trade.close_profit_abs) + .filter(Trade.is_open.is_(False), + Trade.close_date >= profitday, + Trade.close_date < (profitday + time_offset(1))) + .order_by(Trade.close_date) + ).all() + # trades = Trade.query.session.query(Trade.close_profit_abs).filter( + # Trade.is_open.is_(False), + # Trade.close_date >= profitday, + # Trade.close_date < (profitday + time_offset(1)) + # ).order_by(Trade.close_date).all() curdayprofit = sum( trade.close_profit_abs for trade in trades if trade.close_profit_abs is not None) @@ -381,14 +389,19 @@ class RPC: """ Returns the X last trades """ order_by: Any = Trade.id if order_by_id else Trade.close_date.desc() if limit: - trades = Trade.get_trades([Trade.is_open.is_(False)]).order_by( - order_by).limit(limit).offset(offset) + trades = Trade._session.execute( + Trade.get_trades_query([Trade.is_open.is_(False)]) + .order_by(order_by) + .limit(limit) + .offset(offset)) else: - trades = Trade.get_trades([Trade.is_open.is_(False)]).order_by( - Trade.close_date.desc()) + trades = Trade._session.execute( + Trade.get_trades_query([Trade.is_open.is_(False)]) + .order_by(Trade.close_date.desc())) output = [trade.to_json() for trade in trades] - total_trades = Trade.get_trades([Trade.is_open.is_(False)]).count() + total_trades = Trade._session.scalar( + select(func.count(Trade.id)).filter(Trade.is_open.is_(False))) return { "trades": output, @@ -436,8 +449,8 @@ class RPC: """ Returns cumulative profit statistics """ trade_filter = ((Trade.is_open.is_(False) & (Trade.close_date >= start_date)) | Trade.is_open.is_(True)) - trades: List[Trade] = Trade.get_trades( - trade_filter, include_orders=False).order_by(Trade.id).all() + trades: Sequence[Trade] = Trade._session.execute(Trade.get_trades_query( + trade_filter, include_orders=False).order_by(Trade.id)).all() profit_all_coin = [] profit_all_ratio = [] diff --git a/tests/persistence/test_persistence.py b/tests/persistence/test_persistence.py index 0598d4134..cd4890db9 100644 --- a/tests/persistence/test_persistence.py +++ b/tests/persistence/test_persistence.py @@ -1793,17 +1793,17 @@ def test_get_trades_proxy(fee, use_db, is_short): @pytest.mark.usefixtures("init_persistence") @pytest.mark.parametrize('is_short', [True, False]) def test_get_trades__query(fee, is_short): - query = Trade.get_trades([]) + query = Trade.get_trades_query([]) # without orders there should be no join issued. - query1 = Trade.get_trades([], include_orders=False) + query1 = Trade.get_trades_query([], include_orders=False) # Empty "with-options -> default - selectin" assert query._with_options == () assert query1._with_options != () create_mock_trades(fee, is_short) - query = Trade.get_trades([]) - query1 = Trade.get_trades([], include_orders=False) + query = Trade.get_trades_query([]) + query1 = Trade.get_trades_query([], include_orders=False) assert query._with_options == () assert query1._with_options != () From d45599ca3b5c64c9a488f8235d2f2284ed400728 Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 15 Mar 2023 21:09:25 +0100 Subject: [PATCH 156/229] Fix some type errors --- freqtrade/data/btanalysis.py | 2 +- freqtrade/persistence/trade_model.py | 27 +++++++++++++-------------- freqtrade/rpc/rpc.py | 4 ++-- 3 files changed, 16 insertions(+), 17 deletions(-) diff --git a/freqtrade/data/btanalysis.py b/freqtrade/data/btanalysis.py index 9772506a7..3567f4112 100644 --- a/freqtrade/data/btanalysis.py +++ b/freqtrade/data/btanalysis.py @@ -373,7 +373,7 @@ def load_trades_from_db(db_url: str, strategy: Optional[str] = None) -> pd.DataF filters = [] if strategy: filters.append(Trade.strategy == strategy) - trades = trade_list_to_dataframe(Trade.get_trades(filters).all()) + trades = trade_list_to_dataframe(list(Trade.get_trades(filters).all())) return trades diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index a2bbd1ee1..58f6c666a 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -7,10 +7,9 @@ from datetime import datetime, timedelta, timezone from math import isclose from typing import Any, ClassVar, Dict, List, Optional, cast -from sqlalchemy import (Enum, Float, ForeignKey, Integer, Result, Select, String, UniqueConstraint, - desc, func, select) -from sqlalchemy.orm import (Mapped, Query, QueryPropertyDescriptor, lazyload, mapped_column, - relationship) +from sqlalchemy import (Enum, Float, ForeignKey, Integer, ScalarResult, Select, String, + UniqueConstraint, desc, func, select) +from sqlalchemy.orm import Mapped, QueryPropertyDescriptor, lazyload, mapped_column, relationship from freqtrade.constants import (DATETIME_PRINT_FORMAT, MATH_CLOSE_PREC, NON_OPEN_EXCHANGE_STATES, BuySell, LongShort) @@ -1154,9 +1153,9 @@ class LocalTrade(): get open trade count """ if Trade.use_db: - return Trade._session.scalar( + return Trade._session.execute( select(func.count(Trade.id)).filter(Trade.is_open.is_(True)) - ) + ).scalar_one() else: return LocalTrade.bt_open_open_trade_count @@ -1335,7 +1334,7 @@ class Trade(ModelBase, LocalTrade): ) @staticmethod - def get_trades_query(trade_filter=None, include_orders: bool = True) -> Select['Trade']: + def get_trades_query(trade_filter=None, include_orders: bool = True) -> Select: """ Helper function to query Trades using filters. NOTE: Not supported in Backtesting. @@ -1360,7 +1359,7 @@ class Trade(ModelBase, LocalTrade): return this_query @staticmethod - def get_trades(trade_filter=None, include_orders: bool = True) -> Query['Trade']: + def get_trades(trade_filter=None, include_orders: bool = True) -> ScalarResult['Trade']: """ Helper function to query Trades using filters. NOTE: Not supported in Backtesting. @@ -1370,7 +1369,7 @@ class Trade(ModelBase, LocalTrade): e.g. `(trade_filter=Trade.id == trade_id)` :return: unsorted query object """ - return Trade._session.execute(Trade.get_trades_query(trade_filter, include_orders)) + return Trade._session.scalars(Trade.get_trades_query(trade_filter, include_orders)) @staticmethod def get_open_order_trades() -> List['Trade']: @@ -1378,7 +1377,7 @@ class Trade(ModelBase, LocalTrade): Returns all open trades NOTE: Not supported in Backtesting. """ - return Trade.get_trades(Trade.open_order_id.isnot(None)).all() + return cast(List[Trade], Trade.get_trades(Trade.open_order_id.isnot(None)).all()) @staticmethod def get_open_trades_without_assigned_fees(): @@ -1408,12 +1407,12 @@ class Trade(ModelBase, LocalTrade): Retrieves total realized profit """ if Trade.use_db: - total_profit = Trade._session.scalar( + total_profit: float = Trade._session.execute( select(func.sum(Trade.close_profit_abs)).filter(Trade.is_open.is_(False)) - ) + ).scalar_one() else: - total_profit = sum( - t.close_profit_abs for t in LocalTrade.get_trades_proxy(is_open=False)) + total_profit = sum(t.close_profit_abs # type: ignore + for t in LocalTrade.get_trades_proxy(is_open=False)) return total_profit or 0 @staticmethod diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index db2b35049..45150423b 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -159,7 +159,7 @@ class RPC: """ # Fetch open trades if trade_ids: - trades: List[Trade] = Trade.get_trades(trade_filter=Trade.id.in_(trade_ids)).all() + trades: Sequence[Trade] = Trade.get_trades(trade_filter=Trade.id.in_(trade_ids)).all() else: trades = Trade.get_open_trades() @@ -449,7 +449,7 @@ class RPC: """ Returns cumulative profit statistics """ trade_filter = ((Trade.is_open.is_(False) & (Trade.close_date >= start_date)) | Trade.is_open.is_(True)) - trades: Sequence[Trade] = Trade._session.execute(Trade.get_trades_query( + trades: Sequence[Trade] = Trade._session.scalars(Trade.get_trades_query( trade_filter, include_orders=False).order_by(Trade.id)).all() profit_all_coin = [] From 8073989c988aa2c07438d994da77893a565e657d Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 15 Mar 2023 21:10:47 +0100 Subject: [PATCH 157/229] Remove more usages of .query --- freqtrade/freqtradebot.py | 2 +- freqtrade/persistence/pairlock_middleware.py | 8 ++++---- freqtrade/rpc/rpc.py | 5 ----- 3 files changed, 5 insertions(+), 10 deletions(-) diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index dfac11347..1c181cb26 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -819,7 +819,7 @@ class FreqtradeBot(LoggingMixin): trade.orders.append(order_obj) trade.recalc_trade_from_orders() - Trade.query.session.add(trade) + Trade._session.add(trade) Trade.commit() # Updating wallets diff --git a/freqtrade/persistence/pairlock_middleware.py b/freqtrade/persistence/pairlock_middleware.py index 5ed131a9b..08c947a83 100644 --- a/freqtrade/persistence/pairlock_middleware.py +++ b/freqtrade/persistence/pairlock_middleware.py @@ -51,8 +51,8 @@ class PairLocks(): active=True ) if PairLocks.use_db: - PairLock.query.session.add(lock) - PairLock.query.session.commit() + PairLock._session.add(lock) + PairLock._session.commit() else: PairLocks.locks.append(lock) return lock @@ -106,7 +106,7 @@ class PairLocks(): for lock in locks: lock.active = False if PairLocks.use_db: - PairLock.query.session.commit() + PairLock._session.commit() @staticmethod def unlock_reason(reason: str, now: Optional[datetime] = None) -> None: @@ -130,7 +130,7 @@ class PairLocks(): for lock in locks: logger.info(f"Releasing lock for {lock.pair} with reason '{reason}'.") lock.active = False - PairLock.query.session.commit() + PairLock._session.commit() else: # used in backtesting mode; don't show log messages for speed locksb = PairLocks.get_pair_locks(None) diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 45150423b..2d29944f8 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -347,11 +347,6 @@ class RPC: Trade.close_date < (profitday + time_offset(1))) .order_by(Trade.close_date) ).all() - # trades = Trade.query.session.query(Trade.close_profit_abs).filter( - # Trade.is_open.is_(False), - # Trade.close_date >= profitday, - # Trade.close_date < (profitday + time_offset(1)) - # ).order_by(Trade.close_date).all() curdayprofit = sum( trade.close_profit_abs for trade in trades if trade.close_profit_abs is not None) From aa54b7770256a72b20ad7e3f548291951dd59ab2 Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 15 Mar 2023 21:12:06 +0100 Subject: [PATCH 158/229] Rename _session to sessoin --- freqtrade/commands/db_commands.py | 2 +- freqtrade/freqtradebot.py | 2 +- freqtrade/persistence/models.py | 12 ++++---- freqtrade/persistence/pairlock.py | 2 +- freqtrade/persistence/pairlock_middleware.py | 8 +++--- freqtrade/persistence/trade_model.py | 30 ++++++++++---------- freqtrade/rpc/rpc.py | 10 +++---- 7 files changed, 33 insertions(+), 33 deletions(-) diff --git a/freqtrade/commands/db_commands.py b/freqtrade/commands/db_commands.py index c424016b1..b4997582d 100644 --- a/freqtrade/commands/db_commands.py +++ b/freqtrade/commands/db_commands.py @@ -20,7 +20,7 @@ def start_convert_db(args: Dict[str, Any]) -> None: config = setup_utils_configuration(args, RunMode.UTIL_NO_EXCHANGE) init_db(config['db_url']) - session_target = Trade._session + session_target = Trade.session init_db(config['db_url_from']) logger.info("Starting db migration.") diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index 1c181cb26..06c8831f5 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -819,7 +819,7 @@ class FreqtradeBot(LoggingMixin): trade.orders.append(order_obj) trade.recalc_trade_from_orders() - Trade._session.add(trade) + Trade.session.add(trade) Trade.commit() # Updating wallets diff --git a/freqtrade/persistence/models.py b/freqtrade/persistence/models.py index d718af2f4..f4058b4eb 100644 --- a/freqtrade/persistence/models.py +++ b/freqtrade/persistence/models.py @@ -54,12 +54,12 @@ def init_db(db_url: str) -> None: # https://docs.sqlalchemy.org/en/13/orm/contextual.html#thread-local-scope # Scoped sessions proxy requests to the appropriate thread-local session. # We should use the scoped_session object - not a seperately initialized version - Trade._session = scoped_session(sessionmaker(bind=engine, autoflush=False)) - Order._session = Trade._session - PairLock._session = Trade._session - Trade.query = Trade._session.query_property() - Order.query = Trade._session.query_property() - PairLock.query = Trade._session.query_property() + Trade.session = scoped_session(sessionmaker(bind=engine, autoflush=False)) + Order.session = Trade.session + PairLock.session = Trade.session + Trade.query = Trade.session.query_property() + Order.query = Trade.session.query_property() + PairLock.query = Trade.session.query_property() previous_tables = inspect(engine).get_table_names() ModelBase.metadata.create_all(engine) diff --git a/freqtrade/persistence/pairlock.py b/freqtrade/persistence/pairlock.py index 1e5699145..0cd595b66 100644 --- a/freqtrade/persistence/pairlock.py +++ b/freqtrade/persistence/pairlock.py @@ -14,7 +14,7 @@ class PairLock(ModelBase): """ __tablename__ = 'pairlocks' query: ClassVar[QueryPropertyDescriptor] - _session: ClassVar[SessionType] + session: ClassVar[SessionType] id: Mapped[int] = mapped_column(primary_key=True) diff --git a/freqtrade/persistence/pairlock_middleware.py b/freqtrade/persistence/pairlock_middleware.py index 08c947a83..e6860bbe6 100644 --- a/freqtrade/persistence/pairlock_middleware.py +++ b/freqtrade/persistence/pairlock_middleware.py @@ -51,8 +51,8 @@ class PairLocks(): active=True ) if PairLocks.use_db: - PairLock._session.add(lock) - PairLock._session.commit() + PairLock.session.add(lock) + PairLock.session.commit() else: PairLocks.locks.append(lock) return lock @@ -106,7 +106,7 @@ class PairLocks(): for lock in locks: lock.active = False if PairLocks.use_db: - PairLock._session.commit() + PairLock.session.commit() @staticmethod def unlock_reason(reason: str, now: Optional[datetime] = None) -> None: @@ -130,7 +130,7 @@ class PairLocks(): for lock in locks: logger.info(f"Releasing lock for {lock.pair} with reason '{reason}'.") lock.active = False - PairLock._session.commit() + PairLock.session.commit() else: # used in backtesting mode; don't show log messages for speed locksb = PairLocks.get_pair_locks(None) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 58f6c666a..0cc7ad4ff 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -37,7 +37,7 @@ class Order(ModelBase): """ __tablename__ = 'orders' query: ClassVar[QueryPropertyDescriptor] - _session: ClassVar[SessionType] + session: ClassVar[SessionType] # Uniqueness should be ensured over pair, order_id # its likely that order_id is unique per Pair on some exchanges. @@ -1153,7 +1153,7 @@ class LocalTrade(): get open trade count """ if Trade.use_db: - return Trade._session.execute( + return Trade.session.execute( select(func.count(Trade.id)).filter(Trade.is_open.is_(True)) ).scalar_one() else: @@ -1189,7 +1189,7 @@ class Trade(ModelBase, LocalTrade): """ __tablename__ = 'trades' query: ClassVar[QueryPropertyDescriptor] - _session: ClassVar[SessionType] + session: ClassVar[SessionType] use_db: bool = True @@ -1289,18 +1289,18 @@ class Trade(ModelBase, LocalTrade): def delete(self) -> None: for order in self.orders: - Order._session.delete(order) + Order.session.delete(order) - Trade._session.delete(self) + Trade.session.delete(self) Trade.commit() @staticmethod def commit(): - Trade._session.commit() + Trade.session.commit() @staticmethod def rollback(): - Trade._session.rollback() + Trade.session.rollback() @staticmethod def get_trades_proxy(*, pair: Optional[str] = None, is_open: Optional[bool] = None, @@ -1369,7 +1369,7 @@ class Trade(ModelBase, LocalTrade): e.g. `(trade_filter=Trade.id == trade_id)` :return: unsorted query object """ - return Trade._session.scalars(Trade.get_trades_query(trade_filter, include_orders)) + return Trade.session.scalars(Trade.get_trades_query(trade_filter, include_orders)) @staticmethod def get_open_order_trades() -> List['Trade']: @@ -1407,7 +1407,7 @@ class Trade(ModelBase, LocalTrade): Retrieves total realized profit """ if Trade.use_db: - total_profit: float = Trade._session.execute( + total_profit: float = Trade.session.execute( select(func.sum(Trade.close_profit_abs)).filter(Trade.is_open.is_(False)) ).scalar_one() else: @@ -1422,7 +1422,7 @@ class Trade(ModelBase, LocalTrade): in stake currency """ if Trade.use_db: - total_open_stake_amount = Trade._session.scalar( + total_open_stake_amount = Trade.session.scalar( select(func.sum(Trade.stake_amount)).filter(Trade.is_open.is_(True)) ) else: @@ -1441,7 +1441,7 @@ class Trade(ModelBase, LocalTrade): start_date = datetime.now(timezone.utc) - timedelta(minutes=minutes) filters.append(Trade.close_date >= start_date) - pair_rates = Trade._session.execute( + pair_rates = Trade.session.execute( select( Trade.pair, func.sum(Trade.close_profit).label('profit_sum'), @@ -1476,7 +1476,7 @@ class Trade(ModelBase, LocalTrade): if (pair is not None): filters.append(Trade.pair == pair) - enter_tag_perf = Trade._session.execute( + enter_tag_perf = Trade.session.execute( select( Trade.enter_tag, func.sum(Trade.close_profit).label('profit_sum'), @@ -1509,7 +1509,7 @@ class Trade(ModelBase, LocalTrade): filters: List = [Trade.is_open.is_(False)] if (pair is not None): filters.append(Trade.pair == pair) - sell_tag_perf = Trade._session.execute( + sell_tag_perf = Trade.session.execute( select( Trade.exit_reason, func.sum(Trade.close_profit).label('profit_sum'), @@ -1542,7 +1542,7 @@ class Trade(ModelBase, LocalTrade): filters: List = [Trade.is_open.is_(False)] if (pair is not None): filters.append(Trade.pair == pair) - mix_tag_perf = Trade._session.execute( + mix_tag_perf = Trade.session.execute( select( Trade.id, Trade.enter_tag, @@ -1589,7 +1589,7 @@ class Trade(ModelBase, LocalTrade): NOTE: Not supported in Backtesting. :returns: Tuple containing (pair, profit_sum) """ - best_pair = Trade._session.execute( + best_pair = Trade.session.execute( select( Trade.pair, func.sum(Trade.close_profit).label('profit_sum') diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 2d29944f8..f86362841 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -340,7 +340,7 @@ class RPC: for day in range(0, timescale): profitday = start_date - time_offset(day) # Only query for necessary columns for performance reasons. - trades = Trade._session.execute( + trades = Trade.session.execute( select(Trade.close_profit_abs) .filter(Trade.is_open.is_(False), Trade.close_date >= profitday, @@ -384,18 +384,18 @@ class RPC: """ Returns the X last trades """ order_by: Any = Trade.id if order_by_id else Trade.close_date.desc() if limit: - trades = Trade._session.execute( + trades = Trade.session.execute( Trade.get_trades_query([Trade.is_open.is_(False)]) .order_by(order_by) .limit(limit) .offset(offset)) else: - trades = Trade._session.execute( + trades = Trade.session.execute( Trade.get_trades_query([Trade.is_open.is_(False)]) .order_by(Trade.close_date.desc())) output = [trade.to_json() for trade in trades] - total_trades = Trade._session.scalar( + total_trades = Trade.session.scalar( select(func.count(Trade.id)).filter(Trade.is_open.is_(False))) return { @@ -444,7 +444,7 @@ class RPC: """ Returns cumulative profit statistics """ trade_filter = ((Trade.is_open.is_(False) & (Trade.close_date >= start_date)) | Trade.is_open.is_(True)) - trades: Sequence[Trade] = Trade._session.scalars(Trade.get_trades_query( + trades: Sequence[Trade] = Trade.session.scalars(Trade.get_trades_query( trade_filter, include_orders=False).order_by(Trade.id)).all() profit_all_coin = [] From 8865af9104f570401ae1bf1e7b0ca7afe7bdf5aa Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 15 Mar 2023 21:19:36 +0100 Subject: [PATCH 159/229] Remove .query from pairlock --- freqtrade/persistence/pairlock.py | 10 ++++------ freqtrade/persistence/pairlock_middleware.py | 6 ++++-- freqtrade/rpc/rpc.py | 2 +- freqtrade/util/binance_mig.py | 3 ++- 4 files changed, 11 insertions(+), 10 deletions(-) diff --git a/freqtrade/persistence/pairlock.py b/freqtrade/persistence/pairlock.py index 0cd595b66..76382b849 100644 --- a/freqtrade/persistence/pairlock.py +++ b/freqtrade/persistence/pairlock.py @@ -1,8 +1,8 @@ from datetime import datetime, timezone from typing import Any, ClassVar, Dict, Optional -from sqlalchemy import String, or_ -from sqlalchemy.orm import Mapped, Query, QueryPropertyDescriptor, mapped_column +from sqlalchemy import ScalarResult, String, or_, select +from sqlalchemy.orm import Mapped, QueryPropertyDescriptor, mapped_column from freqtrade.constants import DATETIME_PRINT_FORMAT from freqtrade.persistence.base import ModelBase, SessionType @@ -37,7 +37,7 @@ class PairLock(ModelBase): f'lock_end_time={lock_end_time}, reason={self.reason}, active={self.active})') @staticmethod - def query_pair_locks(pair: Optional[str], now: datetime, side: str = '*') -> Query: + def query_pair_locks(pair: Optional[str], now: datetime, side: str = '*') -> ScalarResult['PairLock']: """ Get all currently active locks for this pair :param pair: Pair to check for. Returns all current locks if pair is empty @@ -53,9 +53,7 @@ class PairLock(ModelBase): else: filters.append(PairLock.side == '*') - return PairLock.query.filter( - *filters - ) + return PairLock.session.scalars(select(PairLock).filter(*filters)) def to_json(self) -> Dict[str, Any]: return { diff --git a/freqtrade/persistence/pairlock_middleware.py b/freqtrade/persistence/pairlock_middleware.py index e6860bbe6..a8950961e 100644 --- a/freqtrade/persistence/pairlock_middleware.py +++ b/freqtrade/persistence/pairlock_middleware.py @@ -2,6 +2,8 @@ import logging from datetime import datetime, timezone from typing import List, Optional +from sqlalchemy import select + from freqtrade.exchange import timeframe_to_next_date from freqtrade.persistence.models import PairLock @@ -126,7 +128,7 @@ class PairLocks(): PairLock.active.is_(True), PairLock.reason == reason ] - locks = PairLock.query.filter(*filters) + locks = PairLock.session.scalars(select(PairLock).filter(*filters)).all() for lock in locks: logger.info(f"Releasing lock for {lock.pair} with reason '{reason}'.") lock.active = False @@ -170,6 +172,6 @@ class PairLocks(): Return all locks, also locks with expired end date """ if PairLocks.use_db: - return PairLock.query.all() + return PairLock.session.scalars(select(PairLock)).all() else: return PairLocks.locks diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index f86362841..6915c2025 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -959,7 +959,7 @@ class RPC: if pair: locks = PairLocks.get_pair_locks(pair) if lockid: - locks = PairLock.query.filter(PairLock.id == lockid).all() + locks = PairLock.session.scalar(select(PairLock).filter(PairLock.id == lockid)).all() for lock in locks: lock.active = False diff --git a/freqtrade/util/binance_mig.py b/freqtrade/util/binance_mig.py index 708bb1db7..37a2d2ef1 100644 --- a/freqtrade/util/binance_mig.py +++ b/freqtrade/util/binance_mig.py @@ -1,6 +1,7 @@ import logging from packaging import version +from sqlalchemy import select from freqtrade.constants import Config from freqtrade.enums.tradingmode import TradingMode @@ -44,7 +45,7 @@ def _migrate_binance_futures_db(config: Config): # Should symbol be migrated too? # order.symbol = new_pair Trade.commit() - pls = PairLock.query.filter(PairLock.pair.notlike('%:%')) + pls = PairLock.session.scalars(select(PairLock).filter(PairLock.pair.notlike('%:%'))).all() for pl in pls: pl.pair = f"{pl.pair}:{config['stake_currency']}" # print(pls) From ae361e1d5d82adc78578f99c716e63f95a642c9d Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 16 Mar 2023 06:44:53 +0100 Subject: [PATCH 160/229] Update more .query usages --- freqtrade/persistence/pairlock.py | 3 ++- freqtrade/persistence/pairlock_middleware.py | 8 ++++---- freqtrade/persistence/trade_model.py | 8 ++++---- freqtrade/rpc/rpc.py | 4 ++-- 4 files changed, 12 insertions(+), 11 deletions(-) diff --git a/freqtrade/persistence/pairlock.py b/freqtrade/persistence/pairlock.py index 76382b849..af56a392c 100644 --- a/freqtrade/persistence/pairlock.py +++ b/freqtrade/persistence/pairlock.py @@ -37,7 +37,8 @@ class PairLock(ModelBase): f'lock_end_time={lock_end_time}, reason={self.reason}, active={self.active})') @staticmethod - def query_pair_locks(pair: Optional[str], now: datetime, side: str = '*') -> ScalarResult['PairLock']: + def query_pair_locks( + pair: Optional[str], now: datetime, side: str = '*') -> ScalarResult['PairLock']: """ Get all currently active locks for this pair :param pair: Pair to check for. Returns all current locks if pair is empty diff --git a/freqtrade/persistence/pairlock_middleware.py b/freqtrade/persistence/pairlock_middleware.py index a8950961e..0a3d78c4a 100644 --- a/freqtrade/persistence/pairlock_middleware.py +++ b/freqtrade/persistence/pairlock_middleware.py @@ -1,6 +1,6 @@ import logging from datetime import datetime, timezone -from typing import List, Optional +from typing import List, Optional, Sequence from sqlalchemy import select @@ -60,8 +60,8 @@ class PairLocks(): return lock @staticmethod - def get_pair_locks( - pair: Optional[str], now: Optional[datetime] = None, side: str = '*') -> List[PairLock]: + def get_pair_locks(pair: Optional[str], now: Optional[datetime] = None, + side: str = '*') -> Sequence[PairLock]: """ Get all currently active locks for this pair :param pair: Pair to check for. Returns all current locks if pair is empty @@ -167,7 +167,7 @@ class PairLocks(): ) @staticmethod - def get_all_locks() -> List[PairLock]: + def get_all_locks() -> Sequence[PairLock]: """ Return all locks, also locks with expired end date """ diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 0cc7ad4ff..101638828 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -5,7 +5,7 @@ import logging from collections import defaultdict from datetime import datetime, timedelta, timezone from math import isclose -from typing import Any, ClassVar, Dict, List, Optional, cast +from typing import Any, ClassVar, Dict, List, Optional, Sequence, cast from sqlalchemy import (Enum, Float, ForeignKey, Integer, ScalarResult, Select, String, UniqueConstraint, desc, func, select) @@ -263,12 +263,12 @@ class Order(ModelBase): return o @staticmethod - def get_open_orders() -> List['Order']: + def get_open_orders() -> Sequence['Order']: """ Retrieve open orders from the database :return: List of open orders """ - return Order.query.filter(Order.ft_is_open.is_(True)).all() + return Order.session.scalars(select(Order).filter(Order.ft_is_open.is_(True))).all() @staticmethod def order_by_id(order_id: str) -> Optional['Order']: @@ -276,7 +276,7 @@ class Order(ModelBase): Retrieve order based on order_id :return: Order or None """ - return Order.query.filter(Order.order_id == order_id).first() + return Order.session.scalars(select(Order).filter(Order.order_id == order_id)).first() class LocalTrade(): diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 6915c2025..cf1669231 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -954,12 +954,12 @@ class RPC: def _rpc_delete_lock(self, lockid: Optional[int] = None, pair: Optional[str] = None) -> Dict[str, Any]: """ Delete specific lock(s) """ - locks = [] + locks: Sequence[PairLock] = [] if pair: locks = PairLocks.get_pair_locks(pair) if lockid: - locks = PairLock.session.scalar(select(PairLock).filter(PairLock.id == lockid)).all() + locks = PairLock.session.scalars(select(PairLock).filter(PairLock.id == lockid)).all() for lock in locks: lock.active = False From e579ff9532dbcd0c98c462c3dff3c394e8a9fbd4 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 16 Mar 2023 06:48:12 +0100 Subject: [PATCH 161/229] Simplify pairlock querying --- freqtrade/commands/db_commands.py | 2 +- freqtrade/persistence/pairlock.py | 4 ++++ freqtrade/persistence/pairlock_middleware.py | 2 +- freqtrade/persistence/trade_model.py | 13 +++++++------ 4 files changed, 13 insertions(+), 8 deletions(-) diff --git a/freqtrade/commands/db_commands.py b/freqtrade/commands/db_commands.py index b4997582d..c819ca243 100644 --- a/freqtrade/commands/db_commands.py +++ b/freqtrade/commands/db_commands.py @@ -36,7 +36,7 @@ def start_convert_db(args: Dict[str, Any]) -> None: session_target.commit() - for pairlock in PairLock.query: + for pairlock in PairLock.get_all_locks(): pairlock_count += 1 make_transient(pairlock) session_target.add(pairlock) diff --git a/freqtrade/persistence/pairlock.py b/freqtrade/persistence/pairlock.py index af56a392c..e787b5fa0 100644 --- a/freqtrade/persistence/pairlock.py +++ b/freqtrade/persistence/pairlock.py @@ -56,6 +56,10 @@ class PairLock(ModelBase): return PairLock.session.scalars(select(PairLock).filter(*filters)) + @staticmethod + def get_all_locks() -> ScalarResult['PairLock']: + return PairLock.session.scalars(select(PairLock)) + def to_json(self) -> Dict[str, Any]: return { 'id': self.id, diff --git a/freqtrade/persistence/pairlock_middleware.py b/freqtrade/persistence/pairlock_middleware.py index 0a3d78c4a..29169a50d 100644 --- a/freqtrade/persistence/pairlock_middleware.py +++ b/freqtrade/persistence/pairlock_middleware.py @@ -172,6 +172,6 @@ class PairLocks(): Return all locks, also locks with expired end date """ if PairLocks.use_db: - return PairLock.session.scalars(select(PairLock)).all() + return PairLock.get_all_locks().all() else: return PairLocks.locks diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 101638828..892707810 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -1607,12 +1607,13 @@ class Trade(ModelBase, LocalTrade): NOTE: Not supported in Backtesting. :returns: Tuple containing (pair, profit_sum) """ - trading_volume = Order.query.with_entities( - func.sum(Order.cost).label('volume') - ).filter( - Order.order_filled_date >= start_date, - Order.status == 'closed' - ).scalar() + trading_volume = Trade.session.execute( + select( + func.sum(Order.cost).label('volume') + ).filter( + Order.order_filled_date >= start_date, + Order.status == 'closed' + )).scalar_one() return trading_volume @staticmethod From 6ed337faa38bd1a3c83858f438af3aa1060a446e Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 16 Mar 2023 07:04:15 +0100 Subject: [PATCH 162/229] Update several tests to remove .query --- freqtrade/rpc/rpc.py | 4 ++-- tests/conftest.py | 10 +++++----- tests/persistence/test_migrations.py | 6 +++--- tests/persistence/test_persistence.py | 12 ++++++------ tests/rpc/test_rpc_apiserver.py | 12 ++++++------ 5 files changed, 22 insertions(+), 22 deletions(-) diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index cf1669231..eb184c6d6 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -384,13 +384,13 @@ class RPC: """ Returns the X last trades """ order_by: Any = Trade.id if order_by_id else Trade.close_date.desc() if limit: - trades = Trade.session.execute( + trades = Trade.session.scalars( Trade.get_trades_query([Trade.is_open.is_(False)]) .order_by(order_by) .limit(limit) .offset(offset)) else: - trades = Trade.session.execute( + trades = Trade.session.scalars( Trade.get_trades_query([Trade.is_open.is_(False)]) .order_by(Trade.close_date.desc())) diff --git a/tests/conftest.py b/tests/conftest.py index 3c10de4ec..0aa6e70a8 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -299,7 +299,7 @@ def create_mock_trades(fee, is_short: Optional[bool] = False, use_db: bool = Tru """ def add_trade(trade): if use_db: - Trade.query.session.add(trade) + Trade.session.add(trade) else: LocalTrade.add_bt_trade(trade) is_short1 = is_short if is_short is not None else True @@ -332,11 +332,11 @@ def create_mock_trades_with_leverage(fee, use_db: bool = True): Create some fake trades ... """ if use_db: - Trade.query.session.rollback() + Trade.session.rollback() def add_trade(trade): if use_db: - Trade.query.session.add(trade) + Trade.session.add(trade) else: LocalTrade.add_bt_trade(trade) @@ -366,7 +366,7 @@ def create_mock_trades_with_leverage(fee, use_db: bool = True): add_trade(trade) if use_db: - Trade.query.session.flush() + Trade.session.flush() def create_mock_trades_usdt(fee, is_short: Optional[bool] = False, use_db: bool = True): @@ -375,7 +375,7 @@ def create_mock_trades_usdt(fee, is_short: Optional[bool] = False, use_db: bool """ def add_trade(trade): if use_db: - Trade.query.session.add(trade) + Trade.session.add(trade) else: LocalTrade.add_bt_trade(trade) diff --git a/tests/persistence/test_migrations.py b/tests/persistence/test_migrations.py index 2a6959d58..5254164c1 100644 --- a/tests/persistence/test_migrations.py +++ b/tests/persistence/test_migrations.py @@ -21,8 +21,8 @@ spot, margin, futures = TradingMode.SPOT, TradingMode.MARGIN, TradingMode.FUTURE def test_init_create_session(default_conf): # Check if init create a session init_db(default_conf['db_url']) - assert hasattr(Trade, '_session') - assert 'scoped_session' in type(Trade._session).__name__ + assert hasattr(Trade, 'session') + assert 'scoped_session' in type(Trade.session).__name__ def test_init_custom_db_url(default_conf, tmpdir): @@ -34,7 +34,7 @@ def test_init_custom_db_url(default_conf, tmpdir): init_db(default_conf['db_url']) assert Path(filename).is_file() - r = Trade._session.execute(text("PRAGMA journal_mode")) + r = Trade.session.execute(text("PRAGMA journal_mode")) assert r.first() == ('wal',) diff --git a/tests/persistence/test_persistence.py b/tests/persistence/test_persistence.py index cd4890db9..24ab75a2d 100644 --- a/tests/persistence/test_persistence.py +++ b/tests/persistence/test_persistence.py @@ -1494,7 +1494,7 @@ def test_stoploss_reinitialization(default_conf, fee): assert trade.stop_loss_pct == -0.05 assert trade.initial_stop_loss == 0.95 assert trade.initial_stop_loss_pct == -0.05 - Trade.query.session.add(trade) + Trade.session.add(trade) Trade.commit() # Lower stoploss @@ -1556,7 +1556,7 @@ def test_stoploss_reinitialization_leverage(default_conf, fee): assert trade.stop_loss_pct == -0.1 assert trade.initial_stop_loss == 0.98 assert trade.initial_stop_loss_pct == -0.1 - Trade.query.session.add(trade) + Trade.session.add(trade) Trade.commit() # Lower stoploss @@ -1618,7 +1618,7 @@ def test_stoploss_reinitialization_short(default_conf, fee): assert trade.stop_loss_pct == -0.1 assert trade.initial_stop_loss == 1.02 assert trade.initial_stop_loss_pct == -0.1 - Trade.query.session.add(trade) + Trade.session.add(trade) Trade.commit() # Lower stoploss Trade.stoploss_reinitialization(-0.15) @@ -2443,8 +2443,8 @@ def test_order_to_ccxt(limit_buy_order_open): order = Order.parse_from_ccxt_object(limit_buy_order_open, 'mocked', 'buy') order.ft_trade_id = 1 - order.query.session.add(order) - Order.query.session.commit() + order.session.add(order) + Order.session.commit() order_resp = Order.order_by_id(limit_buy_order_open['id']) assert order_resp @@ -2546,7 +2546,7 @@ def test_recalc_trade_from_orders_dca(data) -> None: leverage=1.0, trading_mode=TradingMode.SPOT ) - Trade.query.session.add(trade) + Trade.session.add(trade) for idx, (order, result) in enumerate(data['orders']): amount = order[1] diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index 9c2c3ee3a..5211946ef 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -652,7 +652,7 @@ def test_api_trade_single(botclient, mocker, fee, ticker, markets, is_short): assert_response(rc, 404) assert rc.json()['detail'] == 'Trade not found.' - Trade.query.session.rollback() + Trade.rollback() create_mock_trades(fee, is_short=is_short) rc = client_get(client, f"{BASE_URI}/trade/3") @@ -943,7 +943,7 @@ def test_api_performance(botclient, fee): ) trade.close_profit = trade.calc_profit_ratio(trade.close_rate) trade.close_profit_abs = trade.calc_profit(trade.close_rate) - Trade.query.session.add(trade) + Trade.session.add(trade) trade = Trade( pair='XRP/ETH', @@ -960,7 +960,7 @@ def test_api_performance(botclient, fee): trade.close_profit = trade.calc_profit_ratio(trade.close_rate) trade.close_profit_abs = trade.calc_profit(trade.close_rate) - Trade.query.session.add(trade) + Trade.session.add(trade) Trade.commit() rc = client_get(client, f"{BASE_URI}/performance") @@ -1290,7 +1290,7 @@ def test_api_forceexit(botclient, mocker, ticker, fee, markets): data={"tradeid": "1"}) assert_response(rc, 502) assert rc.json() == {"error": "Error querying /api/v1/forceexit: invalid argument"} - Trade.query.session.rollback() + Trade.rollback() create_mock_trades(fee) trade = Trade.get_trades([Trade.id == 5]).first() @@ -1299,7 +1299,7 @@ def test_api_forceexit(botclient, mocker, ticker, fee, markets): data={"tradeid": "5", "ordertype": "market", "amount": 23}) assert_response(rc) assert rc.json() == {'result': 'Created sell order for trade 5.'} - Trade.query.session.rollback() + Trade.rollback() trade = Trade.get_trades([Trade.id == 5]).first() assert pytest.approx(trade.amount) == 100 @@ -1309,7 +1309,7 @@ def test_api_forceexit(botclient, mocker, ticker, fee, markets): data={"tradeid": "5"}) assert_response(rc) assert rc.json() == {'result': 'Created sell order for trade 5.'} - Trade.query.session.rollback() + Trade.rollback() trade = Trade.get_trades([Trade.id == 5]).first() assert trade.is_open is False From 9d6e973e5b91a8c816557f2ad21ca883292527b0 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 16 Mar 2023 07:25:04 +0100 Subject: [PATCH 163/229] remove .query from most tests --- tests/persistence/test_migrations.py | 9 +- tests/persistence/test_persistence.py | 7 +- tests/plugins/test_pairlocks.py | 6 +- tests/plugins/test_protections.py | 2 +- tests/rpc/test_rpc.py | 9 +- tests/rpc/test_rpc_apiserver.py | 11 +- tests/rpc/test_rpc_telegram.py | 7 +- tests/test_freqtradebot.py | 220 +++++++++++++------------- tests/test_integration.py | 7 +- 9 files changed, 144 insertions(+), 134 deletions(-) diff --git a/tests/persistence/test_migrations.py b/tests/persistence/test_migrations.py index 5254164c1..053d6da12 100644 --- a/tests/persistence/test_migrations.py +++ b/tests/persistence/test_migrations.py @@ -4,7 +4,7 @@ from pathlib import Path from unittest.mock import MagicMock import pytest -from sqlalchemy import create_engine, text +from sqlalchemy import create_engine, select, text from freqtrade.constants import DEFAULT_DB_PROD_URL from freqtrade.enums import TradingMode @@ -235,8 +235,9 @@ def test_migrate_new(mocker, default_conf, fee, caplog): # Run init to test migration init_db(default_conf['db_url']) - assert len(Trade.query.filter(Trade.id == 1).all()) == 1 - trade = Trade.query.filter(Trade.id == 1).first() + trades = Trade.session.scalars(select(Trade).filter(Trade.id == 1)).all() + assert len(trades) == 1 + trade = trades[0] assert trade.fee_open == fee.return_value assert trade.fee_close == fee.return_value assert trade.open_rate_requested is None @@ -404,7 +405,7 @@ def test_migrate_pairlocks(mocker, default_conf, fee, caplog): init_db(default_conf['db_url']) - assert len(PairLock.query.all()) == 2 + assert len(PairLock.get_all_locks().all()) == 2 assert len(PairLock.query.filter(PairLock.pair == '*').all()) == 1 pairlocks = PairLock.query.filter(PairLock.pair == 'ETH/BTC').all() assert len(pairlocks) == 1 diff --git a/tests/persistence/test_persistence.py b/tests/persistence/test_persistence.py index 24ab75a2d..78e97e2e6 100644 --- a/tests/persistence/test_persistence.py +++ b/tests/persistence/test_persistence.py @@ -4,6 +4,7 @@ from types import FunctionType import arrow import pytest +from sqlalchemy import select from freqtrade.constants import DATETIME_PRINT_FORMAT from freqtrade.enums import TradingMode @@ -2575,11 +2576,11 @@ def test_recalc_trade_from_orders_dca(data) -> None: trade.recalc_trade_from_orders() Trade.commit() - orders1 = Order.query.all() + orders1 = Order.session.scalars(select(Order)).all() assert orders1 assert len(orders1) == idx + 1 - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade assert len(trade.orders) == idx + 1 if idx < len(data) - 1: @@ -2596,6 +2597,6 @@ def test_recalc_trade_from_orders_dca(data) -> None: assert pytest.approx(trade.close_profit_abs) == data['end_profit'] assert pytest.approx(trade.close_profit) == data['end_profit_ratio'] assert not trade.is_open - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade assert trade.open_order_id is None diff --git a/tests/plugins/test_pairlocks.py b/tests/plugins/test_pairlocks.py index 0ba9bb746..39bde3cda 100644 --- a/tests/plugins/test_pairlocks.py +++ b/tests/plugins/test_pairlocks.py @@ -14,7 +14,7 @@ def test_PairLocks(use_db): PairLocks.use_db = use_db # No lock should be present if use_db: - assert len(PairLock.query.all()) == 0 + assert len(PairLock.get_all_locks().all()) == 0 assert PairLocks.use_db == use_db @@ -88,13 +88,13 @@ def test_PairLocks(use_db): if use_db: locks = PairLocks.get_all_locks() - locks_db = PairLock.query.all() + locks_db = PairLock.get_all_locks().all() assert len(locks) == len(locks_db) assert len(locks_db) > 0 else: # Nothing was pushed to the database assert len(PairLocks.get_all_locks()) > 0 - assert len(PairLock.query.all()) == 0 + assert len(PairLock.get_all_locks().all()) == 0 # Reset use-db variable PairLocks.reset_locks() PairLocks.use_db = True diff --git a/tests/plugins/test_protections.py b/tests/plugins/test_protections.py index 2bbdf3d4f..5e6128c73 100644 --- a/tests/plugins/test_protections.py +++ b/tests/plugins/test_protections.py @@ -74,7 +74,7 @@ def generate_mock_trade(pair: str, fee: float, is_open: bool, trade.close(close_price) trade.exit_reason = exit_reason - Trade.query.session.add(trade) + Trade.session.add(trade) Trade.commit() return trade diff --git a/tests/rpc/test_rpc.py b/tests/rpc/test_rpc.py index 1a1802c68..7d829bdb6 100644 --- a/tests/rpc/test_rpc.py +++ b/tests/rpc/test_rpc.py @@ -4,6 +4,7 @@ from unittest.mock import ANY, MagicMock, PropertyMock import pytest from numpy import isnan +from sqlalchemy import select from freqtrade.edge import PairInfo from freqtrade.enums import SignalDirection, State, TradingMode @@ -354,7 +355,7 @@ def test_rpc_delete_trade(mocker, default_conf, fee, markets, caplog, is_short): with pytest.raises(RPCException, match='invalid argument'): rpc._rpc_delete('200') - trades = Trade.query.all() + trades = Trade.session.scalars(select(Trade)).all() trades[1].stoploss_order_id = '1234' trades[2].stoploss_order_id = '1234' assert len(trades) > 2 @@ -717,7 +718,7 @@ def test_rpc_force_exit(default_conf, ticker, fee, mocker) -> None: mocker.patch(f'{EXMS}._dry_is_price_crossed', MagicMock(return_value=False)) freqtradebot.enter_positions() # make an limit-buy open trade - trade = Trade.query.filter(Trade.id == '3').first() + trade = Trade.session.scalars(select(Trade).filter(Trade.id == '3')).first() filled_amount = trade.amount / 2 # Fetch order - it's open first, and closed after cancel_order is called. mocker.patch( @@ -753,7 +754,7 @@ def test_rpc_force_exit(default_conf, ticker, fee, mocker) -> None: freqtradebot.config['max_open_trades'] = 3 freqtradebot.enter_positions() - trade = Trade.query.filter(Trade.id == '2').first() + trade = Trade.session.scalars(select(Trade).filter(Trade.id == '2')).first() amount = trade.amount # make an limit-buy open trade, if there is no 'filled', don't sell it mocker.patch( @@ -771,7 +772,7 @@ def test_rpc_force_exit(default_conf, ticker, fee, mocker) -> None: assert cancel_order_mock.call_count == 2 assert trade.amount == amount - trade = Trade.query.filter(Trade.id == '3').first() + trade = Trade.session.scalars(select(Trade).filter(Trade.id == '3')).first() # make an limit-sell open trade mocker.patch( diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index 5211946ef..97319b78b 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -14,6 +14,7 @@ from fastapi import FastAPI, WebSocketDisconnect from fastapi.exceptions import HTTPException from fastapi.testclient import TestClient from requests.auth import _basic_auth_str +from sqlalchemy import select from freqtrade.__init__ import __version__ from freqtrade.enums import CandleType, RunMode, State, TradingMode @@ -624,7 +625,7 @@ def test_api_trades(botclient, mocker, fee, markets, is_short): assert rc.json()['offset'] == 0 create_mock_trades(fee, is_short=is_short) - Trade.query.session.flush() + Trade.session.flush() rc = client_get(client, f"{BASE_URI}/trades") assert_response(rc) @@ -677,7 +678,7 @@ def test_api_delete_trade(botclient, mocker, fee, markets, is_short): create_mock_trades(fee, is_short=is_short) ftbot.strategy.order_types['stoploss_on_exchange'] = True - trades = Trade.query.all() + trades = Trade.session.scalars(select(Trade)).all() trades[1].stoploss_order_id = '1234' Trade.commit() assert len(trades) > 2 @@ -685,7 +686,7 @@ def test_api_delete_trade(botclient, mocker, fee, markets, is_short): rc = client_delete(client, f"{BASE_URI}/trades/1") assert_response(rc) assert rc.json()['result_msg'] == 'Deleted trade 1. Closed 1 open orders.' - assert len(trades) - 1 == len(Trade.query.all()) + assert len(trades) - 1 == len(Trade.session.scalars(select(Trade)).all()) assert cancel_mock.call_count == 1 cancel_mock.reset_mock() @@ -694,11 +695,11 @@ def test_api_delete_trade(botclient, mocker, fee, markets, is_short): assert_response(rc, 502) assert cancel_mock.call_count == 0 - assert len(trades) - 1 == len(Trade.query.all()) + assert len(trades) - 1 == len(Trade.session.scalars(select(Trade)).all()) rc = client_delete(client, f"{BASE_URI}/trades/2") assert_response(rc) assert rc.json()['result_msg'] == 'Deleted trade 2. Closed 2 open orders.' - assert len(trades) - 2 == len(Trade.query.all()) + assert len(trades) - 2 == len(Trade.session.scalars(select(Trade)).all()) assert stoploss_mock.call_count == 1 rc = client_delete(client, f"{BASE_URI}/trades/502") diff --git a/tests/rpc/test_rpc_telegram.py b/tests/rpc/test_rpc_telegram.py index 59b6df489..b1859f581 100644 --- a/tests/rpc/test_rpc_telegram.py +++ b/tests/rpc/test_rpc_telegram.py @@ -14,6 +14,7 @@ import arrow import pytest import time_machine from pandas import DataFrame +from sqlalchemy import select from telegram import Chat, Message, ReplyKeyboardMarkup, Update from telegram.error import BadRequest, NetworkError, TelegramError @@ -692,7 +693,7 @@ def test_profit_handle(default_conf_usdt, update, ticker_usdt, ticker_sell_up, f # Create some test data freqtradebot.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() context = MagicMock() # Test with invalid 2nd argument (should silently pass) @@ -945,7 +946,7 @@ def test_telegram_forceexit_handle(default_conf, update, ticker, fee, # Create some test data freqtradebot.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade # Increase the price and sell it @@ -1020,7 +1021,7 @@ def test_telegram_force_exit_down_handle(default_conf, update, ticker, fee, fetch_ticker=ticker_sell_down ) - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade # /forceexit 1 diff --git a/tests/test_freqtradebot.py b/tests/test_freqtradebot.py index 349655243..49d00a860 100644 --- a/tests/test_freqtradebot.py +++ b/tests/test_freqtradebot.py @@ -10,6 +10,7 @@ from unittest.mock import ANY, MagicMock, PropertyMock, patch import arrow import pytest from pandas import DataFrame +from sqlalchemy import select from freqtrade.constants import CANCEL_REASON, UNLIMITED_STAKE_AMOUNT from freqtrade.enums import (CandleType, ExitCheckTuple, ExitType, RPCMessageType, RunMode, @@ -247,7 +248,7 @@ def test_edge_overrides_stoploss(limit_order, fee, caplog, mocker, patch_get_signal(freqtrade) freqtrade.strategy.min_roi_reached = MagicMock(return_value=False) freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() caplog.clear() ############################################# ticker_val.update({ @@ -278,7 +279,7 @@ def test_total_open_trades_stakes(mocker, default_conf_usdt, ticker_usdt, fee) - freqtrade = FreqtradeBot(default_conf_usdt) patch_get_signal(freqtrade) freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade is not None assert trade.stake_amount == 60.0 @@ -286,7 +287,7 @@ def test_total_open_trades_stakes(mocker, default_conf_usdt, ticker_usdt, fee) - assert trade.open_date is not None freqtrade.enter_positions() - trade = Trade.query.order_by(Trade.id.desc()).first() + trade = Trade.session.scalars(select(Trade).order_by(Trade.id.desc())).first() assert trade is not None assert trade.stake_amount == 60.0 @@ -317,7 +318,7 @@ def test_create_trade(default_conf_usdt, ticker_usdt, limit_order, patch_get_signal(freqtrade, enter_short=is_short, enter_long=not is_short) freqtrade.create_trade('ETH/USDT') - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short assert trade is not None assert pytest.approx(trade.stake_amount) == 60.0 @@ -568,12 +569,12 @@ def test_process_trade_creation(default_conf_usdt, ticker_usdt, limit_order, lim freqtrade = FreqtradeBot(default_conf_usdt) patch_get_signal(freqtrade, enter_short=is_short, enter_long=not is_short) - trades = Trade.query.filter(Trade.is_open.is_(True)).all() + trades = Trade.get_open_trades() assert not trades freqtrade.process() - trades = Trade.query.filter(Trade.is_open.is_(True)).all() + trades = Trade.get_open_trades() assert len(trades) == 1 trade = trades[0] assert trade is not None @@ -640,11 +641,11 @@ def test_process_trade_handling(default_conf_usdt, ticker_usdt, limit_buy_order_ freqtrade = FreqtradeBot(default_conf_usdt) patch_get_signal(freqtrade) - trades = Trade.query.filter(Trade.is_open.is_(True)).all() + trades = Trade.get_open_trades() assert not trades freqtrade.process() - trades = Trade.query.filter(Trade.is_open.is_(True)).all() + trades = Trade.get_open_trades() assert len(trades) == 1 # Nothing happened ... @@ -671,7 +672,7 @@ def test_process_trade_no_whitelist_pair(default_conf_usdt, ticker_usdt, limit_b assert pair not in default_conf_usdt['exchange']['pair_whitelist'] # create open trade not in whitelist - Trade.query.session.add(Trade( + Trade.session.add(Trade( pair=pair, stake_amount=0.001, fee_open=fee.return_value, @@ -681,7 +682,7 @@ def test_process_trade_no_whitelist_pair(default_conf_usdt, ticker_usdt, limit_b open_rate=0.01, exchange='binance', )) - Trade.query.session.add(Trade( + Trade.session.add(Trade( pair='ETH/USDT', stake_amount=0.001, fee_open=fee.return_value, @@ -838,7 +839,7 @@ def test_execute_entry(mocker, default_conf_usdt, fee, limit_order, # Should create an open trade with an open order id # As the order is not fulfilled yet - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short assert trade assert trade.is_open is True @@ -865,7 +866,7 @@ def test_execute_entry(mocker, default_conf_usdt, fee, limit_order, mocker.patch(f'{EXMS}.create_order', MagicMock(return_value=order)) assert freqtrade.execute_entry(pair, stake_amount, is_short=is_short) - trade = Trade.query.all()[2] + trade = Trade.session.scalars(select(Trade)).all()[2] trade.is_short = is_short assert trade assert trade.open_order_id is None @@ -883,7 +884,7 @@ def test_execute_entry(mocker, default_conf_usdt, fee, limit_order, order['id'] = '555' mocker.patch(f'{EXMS}.create_order', MagicMock(return_value=order)) assert freqtrade.execute_entry(pair, stake_amount) - trade = Trade.query.all()[3] + trade = Trade.session.scalars(select(Trade)).all()[3] trade.is_short = is_short assert trade assert trade.open_order_id is None @@ -896,7 +897,7 @@ def test_execute_entry(mocker, default_conf_usdt, fee, limit_order, freqtrade.strategy.custom_stake_amount = lambda **kwargs: 150.0 assert freqtrade.execute_entry(pair, stake_amount, is_short=is_short) - trade = Trade.query.all()[4] + trade = Trade.session.scalars(select(Trade)).all()[4] trade.is_short = is_short assert trade assert pytest.approx(trade.stake_amount) == 150 @@ -905,7 +906,7 @@ def test_execute_entry(mocker, default_conf_usdt, fee, limit_order, order['id'] = '557' freqtrade.strategy.custom_stake_amount = lambda **kwargs: 20 / 0 assert freqtrade.execute_entry(pair, stake_amount, is_short=is_short) - trade = Trade.query.all()[5] + trade = Trade.session.scalars(select(Trade)).all()[5] trade.is_short = is_short assert trade assert pytest.approx(trade.stake_amount) == 2.0 @@ -934,7 +935,7 @@ def test_execute_entry(mocker, default_conf_usdt, fee, limit_order, order['id'] = '5566' freqtrade.strategy.custom_entry_price = lambda **kwargs: 0.508 assert freqtrade.execute_entry(pair, stake_amount, is_short=is_short) - trade = Trade.query.all()[6] + trade = Trade.session.scalars(select(Trade)).all()[6] trade.is_short = is_short assert trade assert trade.open_rate_requested == 0.508 @@ -951,7 +952,7 @@ def test_execute_entry(mocker, default_conf_usdt, fee, limit_order, ) assert freqtrade.execute_entry(pair, stake_amount, is_short=is_short) - trade = Trade.query.all()[7] + trade = Trade.session.scalars(select(Trade)).all()[7] trade.is_short = is_short assert trade assert trade.open_rate_requested == 10 @@ -961,7 +962,7 @@ def test_execute_entry(mocker, default_conf_usdt, fee, limit_order, order['id'] = '5568' freqtrade.strategy.custom_entry_price = lambda **kwargs: "string price" assert freqtrade.execute_entry(pair, stake_amount, is_short=is_short) - trade = Trade.query.all()[8] + trade = Trade.session.scalars(select(Trade)).all()[8] # Trade(id=9, pair=ETH/USDT, amount=0.20000000, is_short=False, # leverage=1.0, open_rate=10.00000000, open_since=...) # Trade(id=9, pair=ETH/USDT, amount=0.60000000, is_short=True, @@ -982,7 +983,7 @@ def test_execute_entry(mocker, default_conf_usdt, fee, limit_order, freqtrade.exchange.get_max_pair_stake_amount = MagicMock(return_value=500) assert freqtrade.execute_entry(pair, 2000, is_short=is_short) - trade = Trade.query.all()[9] + trade = Trade.session.scalars(select(Trade)).all()[9] trade.is_short = is_short assert pytest.approx(trade.stake_amount) == 500 @@ -991,7 +992,7 @@ def test_execute_entry(mocker, default_conf_usdt, fee, limit_order, freqtrade.strategy.leverage.reset_mock() assert freqtrade.execute_entry(pair, 200, leverage_=3) assert freqtrade.strategy.leverage.call_count == 0 - trade = Trade.query.all()[10] + trade = Trade.session.scalars(select(Trade)).all()[10] assert trade.leverage == 1 if trading_mode == 'spot' else 3 @@ -1053,7 +1054,7 @@ def test_execute_entry_min_leverage(mocker, default_conf_usdt, fee, limit_order, freqtrade.strategy.leverage = MagicMock(return_value=5.0) assert freqtrade.execute_entry(pair, stake_amount, is_short=is_short) - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade.leverage == 5.0 # assert trade.stake_amount == 2 @@ -1158,7 +1159,7 @@ def test_handle_stoploss_on_exchange(mocker, default_conf_usdt, fee, caplog, is_ # as a trade actually happened caplog.clear() freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short trade.is_open = True trade.open_order_id = None @@ -1271,7 +1272,7 @@ def test_handle_sle_cancel_cant_recreate(mocker, default_conf_usdt, fee, caplog, patch_get_signal(freqtrade, enter_short=is_short, enter_long=not is_short) freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short trade.is_open = True trade.open_order_id = None @@ -1316,7 +1317,7 @@ def test_create_stoploss_order_invalid_order( freqtrade.strategy.order_types['stoploss_on_exchange'] = True freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short caplog.clear() freqtrade.create_stoploss_order(trade, 200) @@ -1367,7 +1368,7 @@ def test_create_stoploss_order_insufficient_funds( freqtrade.strategy.order_types['stoploss_on_exchange'] = True freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short caplog.clear() freqtrade.create_stoploss_order(trade, 200) @@ -1435,7 +1436,7 @@ def test_handle_stoploss_on_exchange_trailing( patch_get_signal(freqtrade, enter_short=is_short, enter_long=not is_short) freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short trade.is_open = True trade.open_order_id = None @@ -1554,7 +1555,7 @@ def test_handle_stoploss_on_exchange_trailing_error( freqtrade.strategy.order_types['stoploss_on_exchange_interval'] = 60 patch_get_signal(freqtrade, enter_short=is_short, enter_long=not is_short) freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short trade.is_open = True trade.open_order_id = None @@ -1668,7 +1669,7 @@ def test_handle_stoploss_on_exchange_custom_stop( patch_get_signal(freqtrade, enter_short=is_short, enter_long=not is_short) freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short trade.is_open = True trade.open_order_id = None @@ -1796,7 +1797,7 @@ def test_tsl_on_exchange_compatible_with_edge(mocker, edge_conf, fee, limit_orde freqtrade.active_pair_whitelist = freqtrade.edge.adjust(freqtrade.active_pair_whitelist) freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_open = True trade.open_order_id = None trade.stoploss_order_id = 100 @@ -2162,7 +2163,7 @@ def test_handle_trade( freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short assert trade @@ -2217,7 +2218,7 @@ def test_handle_overlapping_signals( freqtrade.enter_positions() # Buy and Sell triggering, so doing nothing ... - trades = Trade.query.all() + trades = Trade.session.scalars(select(Trade)).all() nb_trades = len(trades) assert nb_trades == 0 @@ -2225,7 +2226,7 @@ def test_handle_overlapping_signals( # Buy is triggering, so buying ... patch_get_signal(freqtrade, enter_short=is_short, enter_long=not is_short) freqtrade.enter_positions() - trades = Trade.query.all() + trades = Trade.session.scalars(select(Trade)).all() for trade in trades: trade.is_short = is_short nb_trades = len(trades) @@ -2235,7 +2236,7 @@ def test_handle_overlapping_signals( # Buy and Sell are not triggering, so doing nothing ... patch_get_signal(freqtrade, enter_long=False) assert freqtrade.handle_trade(trades[0]) is False - trades = Trade.query.all() + trades = Trade.session.scalars(select(Trade)).all() for trade in trades: trade.is_short = is_short nb_trades = len(trades) @@ -2248,7 +2249,7 @@ def test_handle_overlapping_signals( else: patch_get_signal(freqtrade, enter_long=True, exit_long=True) assert freqtrade.handle_trade(trades[0]) is False - trades = Trade.query.all() + trades = Trade.session.scalars(select(Trade)).all() for trade in trades: trade.is_short = is_short nb_trades = len(trades) @@ -2260,7 +2261,7 @@ def test_handle_overlapping_signals( patch_get_signal(freqtrade, enter_long=False, exit_short=True) else: patch_get_signal(freqtrade, enter_long=False, exit_long=True) - trades = Trade.query.all() + trades = Trade.session.scalars(select(Trade)).all() for trade in trades: trade.is_short = is_short assert freqtrade.handle_trade(trades[0]) is True @@ -2291,7 +2292,7 @@ def test_handle_trade_roi(default_conf_usdt, ticker_usdt, limit_order_open, fee, freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short trade.is_open = True @@ -2333,7 +2334,7 @@ def test_handle_trade_use_exit_signal( freqtrade.strategy.min_roi_reached = MagicMock(return_value=False) freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short trade.is_open = True @@ -2370,7 +2371,7 @@ def test_close_trade( # Create trade and sell it freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short assert trade @@ -2427,7 +2428,7 @@ def test_manage_open_orders_entry_usercustom( open_trade.is_short = is_short open_trade.orders[0].side = 'sell' if is_short else 'buy' open_trade.orders[0].ft_order_side = 'sell' if is_short else 'buy' - Trade.query.session.add(open_trade) + Trade.session.add(open_trade) Trade.commit() # Ensure default is to return empty (so not mocked yet) @@ -2438,7 +2439,8 @@ def test_manage_open_orders_entry_usercustom( freqtrade.strategy.check_entry_timeout = MagicMock(return_value=False) freqtrade.manage_open_orders() assert cancel_order_mock.call_count == 0 - trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() + trades = Trade.session.scalars( + select(Trade).filter(Trade.open_order_id.is_(open_trade.open_order_id))).all() nb_trades = len(trades) assert nb_trades == 1 assert freqtrade.strategy.check_entry_timeout.call_count == 1 @@ -2446,7 +2448,8 @@ def test_manage_open_orders_entry_usercustom( freqtrade.manage_open_orders() assert cancel_order_mock.call_count == 0 - trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() + trades = Trade.session.scalars( + select(Trade).filter(Trade.open_order_id.is_(open_trade.open_order_id))).all() nb_trades = len(trades) assert nb_trades == 1 assert freqtrade.strategy.check_entry_timeout.call_count == 1 @@ -2456,7 +2459,8 @@ def test_manage_open_orders_entry_usercustom( freqtrade.manage_open_orders() assert cancel_order_wr_mock.call_count == 1 assert rpc_mock.call_count == 2 - trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() + trades = Trade.session.scalars( + select(Trade).filter(Trade.open_order_id.is_(open_trade.open_order_id))).all() nb_trades = len(trades) assert nb_trades == 0 assert freqtrade.strategy.check_entry_timeout.call_count == 1 @@ -2486,7 +2490,7 @@ def test_manage_open_orders_entry( freqtrade = FreqtradeBot(default_conf_usdt) open_trade.is_short = is_short - Trade.query.session.add(open_trade) + Trade.session.add(open_trade) Trade.commit() freqtrade.strategy.check_entry_timeout = MagicMock(return_value=False) @@ -2524,7 +2528,7 @@ def test_adjust_entry_cancel( ) open_trade.is_short = is_short - Trade.query.session.add(open_trade) + Trade.session.add(open_trade) Trade.commit() # Timeout to not interfere @@ -2535,7 +2539,7 @@ def test_adjust_entry_cancel( freqtrade.manage_open_orders() trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() assert len(trades) == 0 - assert len(Order.query.all()) == 0 + assert len(Order.session.scalars(select(Order)).all()) == 0 assert log_has_re( f"{'Sell' if is_short else 'Buy'} order user requested order cancel*", caplog) assert log_has_re( @@ -2565,7 +2569,7 @@ def test_adjust_entry_maintain_replace( ) open_trade.is_short = is_short - Trade.query.session.add(open_trade) + Trade.session.add(open_trade) Trade.commit() # Timeout to not interfere @@ -2586,7 +2590,7 @@ def test_adjust_entry_maintain_replace( freqtrade.manage_open_orders() trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() assert len(trades) == 1 - nb_all_orders = len(Order.query.all()) + nb_all_orders = len(Order.session.scalars(select(Order)).all()) assert nb_all_orders == 2 # New order seems to be in closed status? # nb_open_orders = len(Order.get_open_orders()) @@ -2618,7 +2622,7 @@ def test_check_handle_cancelled_buy( freqtrade = FreqtradeBot(default_conf_usdt) open_trade.orders = [] open_trade.is_short = is_short - Trade.query.session.add(open_trade) + Trade.session.add(open_trade) Trade.commit() # check it does cancel buy orders over the time limit @@ -2649,7 +2653,7 @@ def test_manage_open_orders_buy_exception( freqtrade = FreqtradeBot(default_conf_usdt) open_trade.is_short = is_short - Trade.query.session.add(open_trade) + Trade.session.add(open_trade) Trade.commit() # check it does cancel buy orders over the time limit @@ -2691,7 +2695,7 @@ def test_manage_open_orders_exit_usercustom( open_trade_usdt.close_date = arrow.utcnow().shift(minutes=-601).datetime open_trade_usdt.close_profit_abs = 0.001 - Trade.query.session.add(open_trade_usdt) + Trade.session.add(open_trade_usdt) Trade.commit() # Ensure default is false freqtrade.manage_open_orders() @@ -2771,7 +2775,7 @@ def test_manage_open_orders_exit( open_trade_usdt.close_profit_abs = 0.001 open_trade_usdt.is_short = is_short - Trade.query.session.add(open_trade_usdt) + Trade.session.add(open_trade_usdt) Trade.commit() freqtrade.strategy.check_exit_timeout = MagicMock(return_value=False) @@ -2811,7 +2815,7 @@ def test_check_handle_cancelled_exit( open_trade_usdt.close_date = arrow.utcnow().shift(minutes=-601).datetime open_trade_usdt.is_short = is_short - Trade.query.session.add(open_trade_usdt) + Trade.session.add(open_trade_usdt) Trade.commit() # check it does cancel sell orders over the time limit @@ -2848,7 +2852,7 @@ def test_manage_open_orders_partial( ) freqtrade = FreqtradeBot(default_conf_usdt) prior_stake = open_trade.stake_amount - Trade.query.session.add(open_trade) + Trade.session.add(open_trade) Trade.commit() # check it does cancel buy orders over the time limit @@ -2893,7 +2897,7 @@ def test_manage_open_orders_partial_fee( open_trade.fee_open = fee() open_trade.fee_close = fee() - Trade.query.session.add(open_trade) + Trade.session.add(open_trade) Trade.commit() # cancelling a half-filled order should update the amount to the bought amount # and apply fees if necessary. @@ -2943,7 +2947,7 @@ def test_manage_open_orders_partial_except( open_trade.fee_open = fee() open_trade.fee_close = fee() - Trade.query.session.add(open_trade) + Trade.session.add(open_trade) Trade.commit() # cancelling a half-filled order should update the amount to the bought amount # and apply fees if necessary. @@ -2982,7 +2986,7 @@ def test_manage_open_orders_exception(default_conf_usdt, ticker_usdt, open_trade ) freqtrade = FreqtradeBot(default_conf_usdt) - Trade.query.session.add(open_trade_usdt) + Trade.session.add(open_trade_usdt) Trade.commit() caplog.clear() @@ -3011,7 +3015,7 @@ def test_handle_cancel_enter(mocker, caplog, default_conf_usdt, limit_order, is_ freqtrade._notify_enter_cancel = MagicMock() trade = mock_trade_usdt_4(fee, is_short) - Trade.query.session.add(trade) + Trade.session.add(trade) Trade.commit() l_order['filled'] = 0.0 @@ -3061,7 +3065,7 @@ def test_handle_cancel_enter_exchanges(mocker, caplog, default_conf_usdt, is_sho reason = CANCEL_REASON['TIMEOUT'] trade = mock_trade_usdt_4(fee, is_short) - Trade.query.session.add(trade) + Trade.session.add(trade) Trade.commit() assert freqtrade.handle_cancel_enter(trade, limit_buy_order_canceled_empty, reason) assert cancel_order_mock.call_count == 0 @@ -3095,7 +3099,7 @@ def test_handle_cancel_enter_corder_empty(mocker, default_conf_usdt, limit_order freqtrade = FreqtradeBot(default_conf_usdt) freqtrade._notify_enter_cancel = MagicMock() trade = mock_trade_usdt_4(fee, is_short) - Trade.query.session.add(trade) + Trade.session.add(trade) Trade.commit() l_order['filled'] = 0.0 l_order['status'] = 'open' @@ -3261,7 +3265,7 @@ def test_execute_trade_exit_up(default_conf_usdt, ticker_usdt, fee, ticker_usdt_ freqtrade.enter_positions() rpc_mock.reset_mock() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade.is_short == is_short assert trade assert freqtrade.strategy.confirm_trade_exit.call_count == 0 @@ -3342,7 +3346,7 @@ def test_execute_trade_exit_down(default_conf_usdt, ticker_usdt, fee, ticker_usd # Create some test data freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short assert trade @@ -3415,7 +3419,7 @@ def test_execute_trade_exit_custom_exit_price( freqtrade.enter_positions() rpc_mock.reset_mock() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short assert trade assert freqtrade.strategy.confirm_trade_exit.call_count == 0 @@ -3492,7 +3496,7 @@ def test_execute_trade_exit_down_stoploss_on_exchange_dry_run( # Create some test data freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade.is_short == is_short assert trade @@ -3566,7 +3570,7 @@ def test_execute_trade_exit_sloe_cancel_exception( patch_get_signal(freqtrade) freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() PairLock.session = MagicMock() freqtrade.config['dry_run'] = False @@ -3611,7 +3615,7 @@ def test_execute_trade_exit_with_stoploss_on_exchange( # Create some test data freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short assert trade trades = [trade] @@ -3631,7 +3635,7 @@ def test_execute_trade_exit_with_stoploss_on_exchange( exit_check=ExitCheckTuple(exit_type=ExitType.STOP_LOSS) ) - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short assert trade assert cancel_order.call_count == 1 @@ -3669,7 +3673,7 @@ def test_may_execute_trade_exit_after_stoploss_on_exchange_hit( # Create some test data freqtrade.enter_positions() freqtrade.manage_open_orders() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trades = [trade] assert trade.stoploss_order_id is None @@ -3755,7 +3759,7 @@ def test_execute_trade_exit_market_order( # Create some test data freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short assert trade @@ -3830,7 +3834,7 @@ def test_execute_trade_exit_insufficient_funds_error(default_conf_usdt, ticker_u # Create some test data freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short assert trade @@ -3898,7 +3902,7 @@ def test_exit_profit_only( exit_type=ExitType.NONE)) freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade.is_short == is_short oobj = Order.parse_from_ccxt_object(limit_order[eside], limit_order[eside]['symbol'], eside) trade.update_order(limit_order[eside]) @@ -3941,7 +3945,7 @@ def test_sell_not_enough_balance(default_conf_usdt, limit_order, limit_order_ope freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() amnt = trade.amount oobj = Order.parse_from_ccxt_object(limit_order['buy'], limit_order['buy']['symbol'], 'buy') @@ -4009,7 +4013,7 @@ def test_locked_pairs(default_conf_usdt, ticker_usdt, fee, # Create some test data freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short assert trade @@ -4064,7 +4068,7 @@ def test_ignore_roi_if_entry_signal(default_conf_usdt, limit_order, limit_order_ freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short oobj = Order.parse_from_ccxt_object( limit_order[eside], limit_order[eside]['symbol'], eside) @@ -4114,7 +4118,7 @@ def test_trailing_stop_loss(default_conf_usdt, limit_order_open, freqtrade.strategy.min_roi_reached = MagicMock(return_value=False) freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade.is_short == is_short assert freqtrade.handle_trade(trade) is False @@ -4189,7 +4193,7 @@ def test_trailing_stop_loss_positive( freqtrade.strategy.min_roi_reached = MagicMock(return_value=False) freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade.is_short == is_short oobj = Order.parse_from_ccxt_object(limit_order[eside], limit_order[eside]['symbol'], eside) trade.update_order(limit_order[eside]) @@ -4286,7 +4290,7 @@ def test_disable_ignore_roi_if_entry_signal(default_conf_usdt, limit_order, limi freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short oobj = Order.parse_from_ccxt_object( @@ -4752,7 +4756,7 @@ def test_order_book_depth_of_market( patch_get_signal(freqtrade, enter_short=is_short, enter_long=not is_short) freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() if is_high_delta: assert trade is None else: @@ -4763,7 +4767,7 @@ def test_order_book_depth_of_market( assert trade.open_date is not None assert trade.exchange == 'binance' - assert len(Trade.query.all()) == 1 + assert len(Trade.session.scalars(select(Trade)).all()) == 1 # Simulate fulfilled LIMIT_BUY order for trade oobj = Order.parse_from_ccxt_object( @@ -4860,7 +4864,7 @@ def test_order_book_exit_pricing( freqtrade.enter_positions() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade time.sleep(0.01) # Race condition fix @@ -4932,7 +4936,7 @@ def test_sync_wallet_dry_run(mocker, default_conf_usdt, ticker_usdt, fee, limit_ n = bot.enter_positions() assert n == 2 - trades = Trade.query.all() + trades = Trade.session.scalars(select(Trade)).all() assert len(trades) == 2 bot.config['max_open_trades'] = 3 @@ -4965,7 +4969,7 @@ def test_cancel_all_open_orders(mocker, default_conf_usdt, fee, limit_order, lim freqtrade = get_patched_freqtradebot(mocker, default_conf_usdt) create_mock_trades(fee, is_short=is_short) - trades = Trade.query.all() + trades = Trade.session.scalars(select(Trade)).all() assert len(trades) == MOCK_TRADE_COUNT freqtrade.cancel_all_open_orders() assert buy_mock.call_count == buy_calls @@ -4981,7 +4985,7 @@ def test_check_for_open_trades(mocker, default_conf_usdt, fee, is_short): assert freqtrade.rpc.send_msg.call_count == 0 create_mock_trades(fee, is_short) - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() trade.is_short = is_short trade.is_open = True @@ -5149,7 +5153,7 @@ def test_reupdate_enter_order_fees(mocker, default_conf_usdt, fee, caplog, is_sh exchange='binance', is_short=is_short ) - Trade.query.session.add(trade) + Trade.session.add(trade) freqtrade.handle_insufficient_funds(trade) # assert log_has_re(r"Trying to reupdate buy fees for .*", caplog) @@ -5546,10 +5550,10 @@ def test_position_adjust(mocker, default_conf_usdt, fee) -> None: assert freqtrade.execute_entry(pair, stake_amount) # Should create an closed trade with an no open order id # Order is filled and trade is open - orders = Order.query.all() + orders = Order.session.scalars(select(Order)).all() assert orders assert len(orders) == 1 - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade assert trade.is_open is True assert trade.open_order_id is None @@ -5559,7 +5563,7 @@ def test_position_adjust(mocker, default_conf_usdt, fee) -> None: # Assume it does nothing since order is closed and trade is open freqtrade.update_trades_without_assigned_fees() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade assert trade.is_open is True assert trade.open_order_id is None @@ -5569,7 +5573,7 @@ def test_position_adjust(mocker, default_conf_usdt, fee) -> None: freqtrade.manage_open_orders() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade assert trade.is_open is True assert trade.open_order_id is None @@ -5595,10 +5599,10 @@ def test_position_adjust(mocker, default_conf_usdt, fee) -> None: mocker.patch(f'{EXMS}.fetch_order_or_stoploss_order', MagicMock(return_value=open_dca_order_1)) assert freqtrade.execute_entry(pair, stake_amount, trade=trade) - orders = Order.query.all() + orders = Order.session.scalars(select(Order)).all() assert orders assert len(orders) == 2 - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade assert trade.open_order_id == '651' assert trade.open_rate == 11 @@ -5628,14 +5632,14 @@ def test_position_adjust(mocker, default_conf_usdt, fee) -> None: mocker.patch(f'{EXMS}.fetch_order_or_stoploss_order', fetch_order_mm) freqtrade.update_trades_without_assigned_fees() - orders = Order.query.all() + orders = Order.session.scalars(select(Order)).all() assert orders assert len(orders) == 2 # Assert that the trade is found as open and without fees trades: List[Trade] = Trade.get_open_trades_without_assigned_fees() assert len(trades) == 1 # Assert trade is as expected - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade assert trade.open_order_id == '651' assert trade.open_rate == 11 @@ -5672,14 +5676,14 @@ def test_position_adjust(mocker, default_conf_usdt, fee) -> None: freqtrade.manage_open_orders() # Assert trade is as expected (averaged dca) - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade assert trade.open_order_id is None assert pytest.approx(trade.open_rate) == 9.90909090909 assert trade.amount == 22 assert pytest.approx(trade.stake_amount) == 218 - orders = Order.query.all() + orders = Order.session.scalars(select(Order)).all() assert orders assert len(orders) == 2 @@ -5714,14 +5718,14 @@ def test_position_adjust(mocker, default_conf_usdt, fee) -> None: assert freqtrade.execute_entry(pair, stake_amount, trade=trade) # Assert trade is as expected (averaged dca) - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade assert trade.open_order_id is None assert pytest.approx(trade.open_rate) == 8.729729729729 assert trade.amount == 37 assert trade.stake_amount == 323 - orders = Order.query.all() + orders = Order.session.scalars(select(Order)).all() assert orders assert len(orders) == 3 @@ -5752,7 +5756,7 @@ def test_position_adjust(mocker, default_conf_usdt, fee) -> None: sub_trade_amt=15) # Assert trade is as expected (averaged dca) - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade assert trade.open_order_id is None assert trade.is_open @@ -5760,7 +5764,7 @@ def test_position_adjust(mocker, default_conf_usdt, fee) -> None: assert trade.stake_amount == 192.05405405405406 assert pytest.approx(trade.open_rate) == 8.729729729729 - orders = Order.query.all() + orders = Order.session.scalars(select(Order)).all() assert orders assert len(orders) == 4 @@ -5825,10 +5829,10 @@ def test_position_adjust2(mocker, default_conf_usdt, fee) -> None: assert freqtrade.execute_entry(pair, amount) # Should create an closed trade with an no open order id # Order is filled and trade is open - orders = Order.query.all() + orders = Order.session.scalars(select(Order)).all() assert orders assert len(orders) == 1 - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade assert trade.is_open is True assert trade.open_order_id is None @@ -5838,7 +5842,7 @@ def test_position_adjust2(mocker, default_conf_usdt, fee) -> None: # Assume it does nothing since order is closed and trade is open freqtrade.update_trades_without_assigned_fees() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade assert trade.is_open is True assert trade.open_order_id is None @@ -5848,7 +5852,7 @@ def test_position_adjust2(mocker, default_conf_usdt, fee) -> None: freqtrade.manage_open_orders() - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade assert trade.is_open is True assert trade.open_order_id is None @@ -5884,7 +5888,7 @@ def test_position_adjust2(mocker, default_conf_usdt, fee) -> None: assert len(trades) == 1 # Assert trade is as expected (averaged dca) - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade assert trade.open_order_id is None assert trade.amount == 50 @@ -5893,7 +5897,7 @@ def test_position_adjust2(mocker, default_conf_usdt, fee) -> None: assert pytest.approx(trade.realized_profit) == -152.375 assert pytest.approx(trade.close_profit_abs) == -152.375 - orders = Order.query.all() + orders = Order.session.scalars(select(Order)).all() assert orders assert len(orders) == 2 # Make sure the closed order is found as the second order. @@ -5926,7 +5930,7 @@ def test_position_adjust2(mocker, default_conf_usdt, fee) -> None: sub_trade_amt=amount) # Assert trade is as expected (averaged dca) - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade assert trade.open_order_id is None assert trade.amount == 50 @@ -5935,7 +5939,7 @@ def test_position_adjust2(mocker, default_conf_usdt, fee) -> None: # Trade fully realized assert pytest.approx(trade.realized_profit) == 94.25 assert pytest.approx(trade.close_profit_abs) == 94.25 - orders = Order.query.all() + orders = Order.session.scalars(select(Order)).all() assert orders assert len(orders) == 3 @@ -6020,11 +6024,11 @@ def test_position_adjust3(mocker, default_conf_usdt, fee, data) -> None: exit_check=ExitCheckTuple(exit_type=ExitType.PARTIAL_EXIT), sub_trade_amt=amount) - orders1 = Order.query.all() + orders1 = Order.session.scalars(select(Order)).all() assert orders1 assert len(orders1) == idx + 1 - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade if idx < len(data) - 1: assert trade.is_open is True @@ -6039,7 +6043,7 @@ def test_position_adjust3(mocker, default_conf_usdt, fee, data) -> None: order_obj = trade.select_order(order[0], False) assert order_obj.order_id == f'60{idx}' - trade = Trade.query.first() + trade = Trade.session.scalars(select(Trade)).first() assert trade assert trade.open_order_id is None assert trade.is_open is False diff --git a/tests/test_integration.py b/tests/test_integration.py index 4c57c5669..922285309 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -1,6 +1,7 @@ from unittest.mock import MagicMock import pytest +from sqlalchemy import select from freqtrade.enums import ExitCheckTuple, ExitType, TradingMode from freqtrade.persistence import Trade @@ -91,7 +92,7 @@ def test_may_execute_exit_stoploss_on_exchange_multi(default_conf, ticker, fee, assert freqtrade.strategy.confirm_trade_exit.call_count == 0 wallets_mock.reset_mock() - trades = Trade.query.all() + trades = Trade.session.scalars(select(Trade)).all() # Make sure stoploss-order is open and trade is bought (since we mock update_trade_state) for trade in trades: stoploss_order_closed['id'] = '3' @@ -179,13 +180,13 @@ def test_forcebuy_last_unlimited(default_conf, ticker, fee, mocker, balance_rati n = freqtrade.enter_positions() assert n == 4 - trades = Trade.query.all() + trades = Trade.session.scalars(select(Trade)).all() assert len(trades) == 4 assert freqtrade.wallets.get_trade_stake_amount('XRP/BTC') == result1 rpc._rpc_force_entry('TKN/BTC', None) - trades = Trade.query.all() + trades = Trade.session.scalars(select(Trade)).all() assert len(trades) == 5 for trade in trades: From 4cfbc55d3418d05449a439d754976fd001f900c4 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 16 Mar 2023 18:07:06 +0100 Subject: [PATCH 164/229] Update remaining tests to get rid of .query --- tests/persistence/test_migrations.py | 4 ++-- tests/persistence/test_persistence.py | 1 + tests/plugins/test_pairlist.py | 4 ++-- tests/plugins/test_pairlocks.py | 4 ++-- tests/test_freqtradebot.py | 27 ++++++++++++++++++--------- 5 files changed, 25 insertions(+), 15 deletions(-) diff --git a/tests/persistence/test_migrations.py b/tests/persistence/test_migrations.py index 053d6da12..854d39994 100644 --- a/tests/persistence/test_migrations.py +++ b/tests/persistence/test_migrations.py @@ -406,8 +406,8 @@ def test_migrate_pairlocks(mocker, default_conf, fee, caplog): init_db(default_conf['db_url']) assert len(PairLock.get_all_locks().all()) == 2 - assert len(PairLock.query.filter(PairLock.pair == '*').all()) == 1 - pairlocks = PairLock.query.filter(PairLock.pair == 'ETH/BTC').all() + assert len(PairLock.session.scalars(select(PairLock).filter(PairLock.pair == '*')).all()) == 1 + pairlocks = PairLock.session.scalars(select(PairLock).filter(PairLock.pair == 'ETH/BTC')).all() assert len(pairlocks) == 1 pairlocks[0].pair == 'ETH/BTC' pairlocks[0].side == '*' diff --git a/tests/persistence/test_persistence.py b/tests/persistence/test_persistence.py index 78e97e2e6..db882d56d 100644 --- a/tests/persistence/test_persistence.py +++ b/tests/persistence/test_persistence.py @@ -2017,6 +2017,7 @@ def test_Trade_object_idem(): 'get_open_trades_without_assigned_fees', 'get_open_order_trades', 'get_trades', + 'get_trades_query', 'get_exit_reason_performance', 'get_enter_tag_performance', 'get_mix_tag_performance', diff --git a/tests/plugins/test_pairlist.py b/tests/plugins/test_pairlist.py index 18ee365e2..bc8fe84f1 100644 --- a/tests/plugins/test_pairlist.py +++ b/tests/plugins/test_pairlist.py @@ -711,8 +711,8 @@ def test_PrecisionFilter_error(mocker, whitelist_conf) -> None: def test_PerformanceFilter_error(mocker, whitelist_conf, caplog) -> None: whitelist_conf['pairlists'] = [{"method": "StaticPairList"}, {"method": "PerformanceFilter"}] - if hasattr(Trade, 'query'): - del Trade.query + if hasattr(Trade, 'session'): + del Trade.session mocker.patch(f'{EXMS}.exchange_has', MagicMock(return_value=True)) exchange = get_patched_exchange(mocker, whitelist_conf) pm = PairListManager(exchange, whitelist_conf, MagicMock()) diff --git a/tests/plugins/test_pairlocks.py b/tests/plugins/test_pairlocks.py index 39bde3cda..6b7112f98 100644 --- a/tests/plugins/test_pairlocks.py +++ b/tests/plugins/test_pairlocks.py @@ -107,7 +107,7 @@ def test_PairLocks_getlongestlock(use_db): # No lock should be present PairLocks.use_db = use_db if use_db: - assert len(PairLock.query.all()) == 0 + assert len(PairLock.get_all_locks().all()) == 0 assert PairLocks.use_db == use_db @@ -139,7 +139,7 @@ def test_PairLocks_reason(use_db): PairLocks.use_db = use_db # No lock should be present if use_db: - assert len(PairLock.query.all()) == 0 + assert len(PairLock.get_all_locks().all()) == 0 assert PairLocks.use_db == use_db diff --git a/tests/test_freqtradebot.py b/tests/test_freqtradebot.py index 49d00a860..cea70ec48 100644 --- a/tests/test_freqtradebot.py +++ b/tests/test_freqtradebot.py @@ -2499,7 +2499,8 @@ def test_manage_open_orders_entry( freqtrade.manage_open_orders() assert cancel_order_mock.call_count == 1 assert rpc_mock.call_count == 2 - trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() + trades = Trade.session.scalars( + select(Trade).filter(Trade.open_order_id.is_(open_trade.open_order_id))).all() nb_trades = len(trades) assert nb_trades == 0 # Custom user buy-timeout is never called @@ -2537,7 +2538,8 @@ def test_adjust_entry_cancel( # check that order is cancelled freqtrade.strategy.adjust_entry_price = MagicMock(return_value=None) freqtrade.manage_open_orders() - trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() + trades = Trade.session.scalars( + select(Trade).filter(Trade.open_order_id.is_(open_trade.open_order_id))).all() assert len(trades) == 0 assert len(Order.session.scalars(select(Order)).all()) == 0 assert log_has_re( @@ -2578,7 +2580,8 @@ def test_adjust_entry_maintain_replace( # Check that order is maintained freqtrade.strategy.adjust_entry_price = MagicMock(return_value=old_order['price']) freqtrade.manage_open_orders() - trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() + trades = Trade.session.scalars( + select(Trade).filter(Trade.open_order_id.is_(open_trade.open_order_id))).all() assert len(trades) == 1 assert len(Order.get_open_orders()) == 1 # Entry adjustment is called @@ -2588,7 +2591,8 @@ def test_adjust_entry_maintain_replace( freqtrade.get_valid_enter_price_and_stake = MagicMock(return_value={100, 10, 1}) freqtrade.strategy.adjust_entry_price = MagicMock(return_value=1234) freqtrade.manage_open_orders() - trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() + trades = Trade.session.scalars( + select(Trade).filter(Trade.open_order_id.is_(open_trade.open_order_id))).all() assert len(trades) == 1 nb_all_orders = len(Order.session.scalars(select(Order)).all()) assert nb_all_orders == 2 @@ -2629,7 +2633,8 @@ def test_check_handle_cancelled_buy( freqtrade.manage_open_orders() assert cancel_order_mock.call_count == 0 assert rpc_mock.call_count == 2 - trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() + trades = Trade.session.scalars( + select(Trade).filter(Trade.open_order_id.is_(open_trade.open_order_id))).all() assert len(trades) == 0 assert log_has_re( f"{'Sell' if is_short else 'Buy'} order cancelled on exchange for Trade.*", caplog) @@ -2660,7 +2665,8 @@ def test_manage_open_orders_buy_exception( freqtrade.manage_open_orders() assert cancel_order_mock.call_count == 0 assert rpc_mock.call_count == 1 - trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() + trades = Trade.session.scalars( + select(Trade).filter(Trade.open_order_id.is_(open_trade.open_order_id))).all() nb_trades = len(trades) assert nb_trades == 1 @@ -2860,7 +2866,8 @@ def test_manage_open_orders_partial( freqtrade.manage_open_orders() assert cancel_order_mock.call_count == 1 assert rpc_mock.call_count == 3 - trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() + trades = Trade.session.scalars( + select(Trade).filter(Trade.open_order_id.is_(open_trade.open_order_id))).all() assert len(trades) == 1 assert trades[0].amount == 23.0 assert trades[0].stake_amount == open_trade.open_rate * trades[0].amount / leverage @@ -2907,7 +2914,8 @@ def test_manage_open_orders_partial_fee( assert cancel_order_mock.call_count == 1 assert rpc_mock.call_count == 3 - trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() + trades = Trade.session.scalars( + select(Trade).filter(Trade.open_order_id.is_(open_trade.open_order_id))).all() assert len(trades) == 1 # Verify that trade has been updated assert trades[0].amount == (limit_buy_order_old_partial['amount'] - @@ -2957,7 +2965,8 @@ def test_manage_open_orders_partial_except( assert cancel_order_mock.call_count == 1 assert rpc_mock.call_count == 3 - trades = Trade.query.filter(Trade.open_order_id.is_(open_trade.open_order_id)).all() + trades = Trade.session.scalars( + select(Trade).filter(Trade.open_order_id.is_(open_trade.open_order_id))).all() assert len(trades) == 1 # Verify that trade has been updated From b7709126f9430a87bfcd515f4f37b6fa11e4f17c Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 16 Mar 2023 18:07:22 +0100 Subject: [PATCH 165/229] remove .query completely --- freqtrade/commands/db_commands.py | 8 ++++---- freqtrade/persistence/models.py | 3 --- freqtrade/persistence/pairlock.py | 3 +-- freqtrade/persistence/trade_model.py | 4 +--- 4 files changed, 6 insertions(+), 12 deletions(-) diff --git a/freqtrade/commands/db_commands.py b/freqtrade/commands/db_commands.py index c819ca243..d83605c6f 100644 --- a/freqtrade/commands/db_commands.py +++ b/freqtrade/commands/db_commands.py @@ -1,7 +1,7 @@ import logging from typing import Any, Dict -from sqlalchemy import func +from sqlalchemy import func, select from freqtrade.configuration.config_setup import setup_utils_configuration from freqtrade.enums import RunMode @@ -43,9 +43,9 @@ def start_convert_db(args: Dict[str, Any]) -> None: session_target.commit() # Update sequences - max_trade_id = session_target.query(func.max(Trade.id)).scalar() - max_order_id = session_target.query(func.max(Order.id)).scalar() - max_pairlock_id = session_target.query(func.max(PairLock.id)).scalar() + max_trade_id = session_target.scalar(select(func.max(Trade.id))) + max_order_id = session_target.scalar(select(func.max(Order.id))) + max_pairlock_id = session_target.scalar(select(func.max(PairLock.id))) set_sequence_ids(session_target.get_bind(), trade_id=max_trade_id, diff --git a/freqtrade/persistence/models.py b/freqtrade/persistence/models.py index f4058b4eb..eee07e61c 100644 --- a/freqtrade/persistence/models.py +++ b/freqtrade/persistence/models.py @@ -57,9 +57,6 @@ def init_db(db_url: str) -> None: Trade.session = scoped_session(sessionmaker(bind=engine, autoflush=False)) Order.session = Trade.session PairLock.session = Trade.session - Trade.query = Trade.session.query_property() - Order.query = Trade.session.query_property() - PairLock.query = Trade.session.query_property() previous_tables = inspect(engine).get_table_names() ModelBase.metadata.create_all(engine) diff --git a/freqtrade/persistence/pairlock.py b/freqtrade/persistence/pairlock.py index e787b5fa0..1b254c2b2 100644 --- a/freqtrade/persistence/pairlock.py +++ b/freqtrade/persistence/pairlock.py @@ -2,7 +2,7 @@ from datetime import datetime, timezone from typing import Any, ClassVar, Dict, Optional from sqlalchemy import ScalarResult, String, or_, select -from sqlalchemy.orm import Mapped, QueryPropertyDescriptor, mapped_column +from sqlalchemy.orm import Mapped, mapped_column from freqtrade.constants import DATETIME_PRINT_FORMAT from freqtrade.persistence.base import ModelBase, SessionType @@ -13,7 +13,6 @@ class PairLock(ModelBase): Pair Locks database model. """ __tablename__ = 'pairlocks' - query: ClassVar[QueryPropertyDescriptor] session: ClassVar[SessionType] id: Mapped[int] = mapped_column(primary_key=True) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 892707810..27be0d726 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -9,7 +9,7 @@ from typing import Any, ClassVar, Dict, List, Optional, Sequence, cast from sqlalchemy import (Enum, Float, ForeignKey, Integer, ScalarResult, Select, String, UniqueConstraint, desc, func, select) -from sqlalchemy.orm import Mapped, QueryPropertyDescriptor, lazyload, mapped_column, relationship +from sqlalchemy.orm import Mapped, lazyload, mapped_column, relationship from freqtrade.constants import (DATETIME_PRINT_FORMAT, MATH_CLOSE_PREC, NON_OPEN_EXCHANGE_STATES, BuySell, LongShort) @@ -36,7 +36,6 @@ class Order(ModelBase): Mirrors CCXT Order structure """ __tablename__ = 'orders' - query: ClassVar[QueryPropertyDescriptor] session: ClassVar[SessionType] # Uniqueness should be ensured over pair, order_id @@ -1188,7 +1187,6 @@ class Trade(ModelBase, LocalTrade): Note: Fields must be aligned with LocalTrade class """ __tablename__ = 'trades' - query: ClassVar[QueryPropertyDescriptor] session: ClassVar[SessionType] use_db: bool = True From e3e4fbd5ba397558bdd90f985759583e71026f61 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 16 Mar 2023 19:24:37 +0100 Subject: [PATCH 166/229] Minor test fix --- tests/rpc/test_rpc_telegram.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/rpc/test_rpc_telegram.py b/tests/rpc/test_rpc_telegram.py index 1dc255b3e..59b6df489 100644 --- a/tests/rpc/test_rpc_telegram.py +++ b/tests/rpc/test_rpc_telegram.py @@ -302,8 +302,7 @@ def test_telegram_status_closed_trade(default_conf, update, mocker, fee) -> None telegram, _, msg_mock = get_telegram_testobject(mocker, default_conf) create_mock_trades(fee) - trades = Trade.get_trades([Trade.is_open.is_(False)]) - trade = trades[0] + trade = Trade.get_trades([Trade.is_open.is_(False)]).first() context = MagicMock() context.args = [str(trade.id)] telegram._status(update=update, context=context) From 774eacc561915ff5fdb78d1552089158766a13eb Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 14 Mar 2023 20:27:14 +0100 Subject: [PATCH 167/229] Attempt push to ghcr.io --- .github/workflows/ci.yml | 14 +++++++++++--- build_helpers/publish_docker_arm64.sh | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7e0483c3d..a1fa487a5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,7 +16,8 @@ on: concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true - +permissions: + repository-projects: read jobs: build_linux: @@ -321,7 +322,6 @@ jobs: build_linux_online: # Run pytest with "live" checks runs-on: ubuntu-22.04 - # permissions: steps: - uses: actions/checkout@v3 @@ -472,6 +472,8 @@ jobs: build_helpers/publish_docker_multi.sh deploy_arm: + permissions: + packages: write needs: [ deploy ] # Only run on 64bit machines runs-on: [self-hosted, linux, ARM64] @@ -492,9 +494,15 @@ jobs: run: | echo "${DOCKER_PASSWORD}" | docker login --username ${DOCKER_USERNAME} --password-stdin + - name: GHCR.io login + env: + GHCR_USERNAME: ${{ github.actor }} + GHCR_PASSWORD: ${{ secrets.GITHUB_TOKEN }} + run: | + echo "${GHCR_PASSWORD}" | docker login ghcr.io --username ${GHCR_USERNAME} --password-stdin + - name: Build and test and push docker images env: - IMAGE_NAME: freqtradeorg/freqtrade BRANCH_NAME: ${{ steps.extract_branch.outputs.branch }} run: | build_helpers/publish_docker_arm64.sh diff --git a/build_helpers/publish_docker_arm64.sh b/build_helpers/publish_docker_arm64.sh index f3cedff2e..c362ee825 100755 --- a/build_helpers/publish_docker_arm64.sh +++ b/build_helpers/publish_docker_arm64.sh @@ -3,6 +3,8 @@ # Use BuildKit, otherwise building on ARM fails export DOCKER_BUILDKIT=1 +IMAGE_NAME=freqtradeorg/freqtrade +GHCR_IMAGE_NAME=ghcr.io/freqtrade/freqtrade # Replace / with _ to create a valid tag TAG=$(echo "${BRANCH_NAME}" | sed -e "s/\//_/g") TAG_PLOT=${TAG}_plot @@ -82,6 +84,18 @@ docker manifest push -p ${IMAGE_NAME}:${TAG_FREQAI} docker manifest create ${IMAGE_NAME}:${TAG_FREQAI_RL} ${CACHE_IMAGE}:${TAG_FREQAI_RL} ${CACHE_IMAGE}:${TAG_FREQAI_RL_ARM} docker manifest push -p ${IMAGE_NAME}:${TAG_FREQAI_RL} +# Retag images for GHCR +docker tag ${IMAGE_NAME}:${TAG} ${GHCR_IMAGE_NAME}:${TAG} +docker tag ${IMAGE_NAME}:${TAG_PLOT} ${GHCR_IMAGE_NAME}:${TAG_PLOT} +docker tag ${IMAGE_NAME}:${TAG_FREQAI} ${GHCR_IMAGE_NAME}:${TAG_FREQAI} +docker tag ${IMAGE_NAME}:${TAG_FREQAI_RL} ${GHCR_IMAGE_NAME}:${TAG_FREQAI_RL} + +# Push GHCR iamges +docker push ${GHCR_IMAGE_NAME}:${TAG} +docker push ${GHCR_IMAGE_NAME}:${TAG_PLOT} +docker push ${GHCR_IMAGE_NAME}:${TAG_FREQAI} +docker push ${GHCR_IMAGE_NAME}:${TAG_FREQAI_RL} + # Tag as latest for develop builds if [ "${TAG}" = "develop" ]; then echo 'Tagging image as latest' From db0f449d93d5b79b0b3d5230f8a56ba145d19256 Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 15 Mar 2023 06:46:31 +0100 Subject: [PATCH 168/229] Use docker manifest for GHCR builds --- build_helpers/publish_docker_arm64.sh | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/build_helpers/publish_docker_arm64.sh b/build_helpers/publish_docker_arm64.sh index c362ee825..e29cd695d 100755 --- a/build_helpers/publish_docker_arm64.sh +++ b/build_helpers/publish_docker_arm64.sh @@ -84,23 +84,27 @@ docker manifest push -p ${IMAGE_NAME}:${TAG_FREQAI} docker manifest create ${IMAGE_NAME}:${TAG_FREQAI_RL} ${CACHE_IMAGE}:${TAG_FREQAI_RL} ${CACHE_IMAGE}:${TAG_FREQAI_RL_ARM} docker manifest push -p ${IMAGE_NAME}:${TAG_FREQAI_RL} -# Retag images for GHCR -docker tag ${IMAGE_NAME}:${TAG} ${GHCR_IMAGE_NAME}:${TAG} -docker tag ${IMAGE_NAME}:${TAG_PLOT} ${GHCR_IMAGE_NAME}:${TAG_PLOT} -docker tag ${IMAGE_NAME}:${TAG_FREQAI} ${GHCR_IMAGE_NAME}:${TAG_FREQAI} -docker tag ${IMAGE_NAME}:${TAG_FREQAI_RL} ${GHCR_IMAGE_NAME}:${TAG_FREQAI_RL} +# Recreate multiarch images for GHCR +docker manifest create ${GHCR_IMAGE_NAME}:${TAG} ${CACHE_IMAGE}:${TAG} ${CACHE_IMAGE}:${TAG_ARM} ${IMAGE_NAME}:${TAG_PI} +docker manifest push -p ${GHCR_IMAGE_NAME}:${TAG} -# Push GHCR iamges -docker push ${GHCR_IMAGE_NAME}:${TAG} -docker push ${GHCR_IMAGE_NAME}:${TAG_PLOT} -docker push ${GHCR_IMAGE_NAME}:${TAG_FREQAI} -docker push ${GHCR_IMAGE_NAME}:${TAG_FREQAI_RL} +docker manifest create ${GHCR_IMAGE_NAME}:${TAG_PLOT} ${CACHE_IMAGE}:${TAG_PLOT} ${CACHE_IMAGE}:${TAG_PLOT_ARM} +docker manifest push -p ${GHCR_IMAGE_NAME}:${TAG_PLOT} + +docker manifest create ${GHCR_IMAGE_NAME}:${TAG_FREQAI} ${CACHE_IMAGE}:${TAG_FREQAI} ${CACHE_IMAGE}:${TAG_FREQAI_ARM} +docker manifest push -p ${GHCR_IMAGE_NAME}:${TAG_FREQAI} + +docker manifest create ${GHCR_IMAGE_NAME}:${TAG_FREQAI_RL} ${CACHE_IMAGE}:${TAG_FREQAI_RL} ${CACHE_IMAGE}:${TAG_FREQAI_RL_ARM} +docker manifest push -p ${GHCR_IMAGE_NAME}:${TAG_FREQAI_RL} # Tag as latest for develop builds if [ "${TAG}" = "develop" ]; then echo 'Tagging image as latest' docker manifest create ${IMAGE_NAME}:latest ${CACHE_IMAGE}:${TAG_ARM} ${IMAGE_NAME}:${TAG_PI} ${CACHE_IMAGE}:${TAG} docker manifest push -p ${IMAGE_NAME}:latest + + docker manifest create ${GHCR_IMAGE_NAME}:latest ${CACHE_IMAGE}:${TAG_ARM} ${IMAGE_NAME}:${TAG_PI} ${CACHE_IMAGE}:${TAG} + docker manifest push -p ${GHCR_IMAGE_NAME}:latest fi docker images From 0d3de0701256b351d66b53a4001b2fae4d69ab7f Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 15 Mar 2023 19:06:08 +0100 Subject: [PATCH 169/229] use Crane to move images around --- .github/workflows/ci.yml | 15 ++++++++------- build_helpers/publish_docker_arm64.sh | 27 ++++++++++++--------------- build_helpers/publish_docker_multi.sh | 3 ++- 3 files changed, 22 insertions(+), 23 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a1fa487a5..f09e5feac 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -466,7 +466,6 @@ jobs: - name: Build and test and push docker images env: - IMAGE_NAME: freqtradeorg/freqtrade BRANCH_NAME: ${{ steps.extract_branch.outputs.branch }} run: | build_helpers/publish_docker_multi.sh @@ -494,16 +493,18 @@ jobs: run: | echo "${DOCKER_PASSWORD}" | docker login --username ${DOCKER_USERNAME} --password-stdin - - name: GHCR.io login - env: - GHCR_USERNAME: ${{ github.actor }} - GHCR_PASSWORD: ${{ secrets.GITHUB_TOKEN }} - run: | - echo "${GHCR_PASSWORD}" | docker login ghcr.io --username ${GHCR_USERNAME} --password-stdin + # - name: GHCR.io login + # env: + # GHCR_USERNAME: ${{ github.actor }} + # GHCR_PASSWORD: ${{ secrets.GITHUB_TOKEN }} + # run: | + # echo "${GHCR_PASSWORD}" | docker login ghcr.io --username ${GHCR_USERNAME} --password-stdin - name: Build and test and push docker images env: BRANCH_NAME: ${{ steps.extract_branch.outputs.branch }} + GHCR_USERNAME: ${{ github.actor }} + GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | build_helpers/publish_docker_arm64.sh diff --git a/build_helpers/publish_docker_arm64.sh b/build_helpers/publish_docker_arm64.sh index e29cd695d..3de113d37 100755 --- a/build_helpers/publish_docker_arm64.sh +++ b/build_helpers/publish_docker_arm64.sh @@ -4,7 +4,9 @@ export DOCKER_BUILDKIT=1 IMAGE_NAME=freqtradeorg/freqtrade +CACHE_IMAGE=freqtradeorg/freqtrade_cache GHCR_IMAGE_NAME=ghcr.io/freqtrade/freqtrade + # Replace / with _ to create a valid tag TAG=$(echo "${BRANCH_NAME}" | sed -e "s/\//_/g") TAG_PLOT=${TAG}_plot @@ -16,7 +18,6 @@ TAG_ARM=${TAG}_arm TAG_PLOT_ARM=${TAG_PLOT}_arm TAG_FREQAI_ARM=${TAG_FREQAI}_arm TAG_FREQAI_RL_ARM=${TAG_FREQAI_RL}_arm -CACHE_IMAGE=freqtradeorg/freqtrade_cache echo "Running for ${TAG}" @@ -40,13 +41,13 @@ if [ $? -ne 0 ]; then echo "failed building multiarch images" return 1 fi -# Tag image for upload and next build step -docker tag freqtrade:$TAG_ARM ${CACHE_IMAGE}:$TAG_ARM docker build --cache-from freqtrade:${TAG_ARM} --build-arg sourceimage=${CACHE_IMAGE} --build-arg sourcetag=${TAG_ARM} -t freqtrade:${TAG_PLOT_ARM} -f docker/Dockerfile.plot . docker build --cache-from freqtrade:${TAG_ARM} --build-arg sourceimage=${CACHE_IMAGE} --build-arg sourcetag=${TAG_ARM} -t freqtrade:${TAG_FREQAI_ARM} -f docker/Dockerfile.freqai . docker build --cache-from freqtrade:${TAG_ARM} --build-arg sourceimage=${CACHE_IMAGE} --build-arg sourcetag=${TAG_ARM} -t freqtrade:${TAG_FREQAI_RL_ARM} -f docker/Dockerfile.freqai_rl . +# Tag image for upload and next build step +docker tag freqtrade:$TAG_ARM ${CACHE_IMAGE}:$TAG_ARM docker tag freqtrade:$TAG_PLOT_ARM ${CACHE_IMAGE}:$TAG_PLOT_ARM docker tag freqtrade:$TAG_FREQAI_ARM ${CACHE_IMAGE}:$TAG_FREQAI_ARM docker tag freqtrade:$TAG_FREQAI_RL_ARM ${CACHE_IMAGE}:$TAG_FREQAI_RL_ARM @@ -61,7 +62,6 @@ fi docker images -# docker push ${IMAGE_NAME} docker push ${CACHE_IMAGE}:$TAG_PLOT_ARM docker push ${CACHE_IMAGE}:$TAG_FREQAI_ARM docker push ${CACHE_IMAGE}:$TAG_FREQAI_RL_ARM @@ -84,18 +84,16 @@ docker manifest push -p ${IMAGE_NAME}:${TAG_FREQAI} docker manifest create ${IMAGE_NAME}:${TAG_FREQAI_RL} ${CACHE_IMAGE}:${TAG_FREQAI_RL} ${CACHE_IMAGE}:${TAG_FREQAI_RL_ARM} docker manifest push -p ${IMAGE_NAME}:${TAG_FREQAI_RL} -# Recreate multiarch images for GHCR -docker manifest create ${GHCR_IMAGE_NAME}:${TAG} ${CACHE_IMAGE}:${TAG} ${CACHE_IMAGE}:${TAG_ARM} ${IMAGE_NAME}:${TAG_PI} -docker manifest push -p ${GHCR_IMAGE_NAME}:${TAG} +# copy images to ghcr.io -docker manifest create ${GHCR_IMAGE_NAME}:${TAG_PLOT} ${CACHE_IMAGE}:${TAG_PLOT} ${CACHE_IMAGE}:${TAG_PLOT_ARM} -docker manifest push -p ${GHCR_IMAGE_NAME}:${TAG_PLOT} +alias crane="docker run --rm -v $(pwd)/crane:/home/nonroot/.docker/ gcr.io/go-containerregistry/crane" -docker manifest create ${GHCR_IMAGE_NAME}:${TAG_FREQAI} ${CACHE_IMAGE}:${TAG_FREQAI} ${CACHE_IMAGE}:${TAG_FREQAI_ARM} -docker manifest push -p ${GHCR_IMAGE_NAME}:${TAG_FREQAI} +echo "${GHCR_TOKEN}" | crane auth login ghcr.io -u ${GHCR_USER} --password-stdin -docker manifest create ${GHCR_IMAGE_NAME}:${TAG_FREQAI_RL} ${CACHE_IMAGE}:${TAG_FREQAI_RL} ${CACHE_IMAGE}:${TAG_FREQAI_RL_ARM} -docker manifest push -p ${GHCR_IMAGE_NAME}:${TAG_FREQAI_RL} +crane copy ${IMAGE_NAME}:${TAG} ${GHCR_IMAGE_NAME}:${TAG} +crane copy ${IMAGE_NAME}:${TAG_PLOT} ${GHCR_IMAGE_NAME}:${TAG_PLOT} +crane copy ${IMAGE_NAME}:${TAG_FREQAI} ${GHCR_IMAGE_NAME}:${TAG_FREQAI} +crane copy ${IMAGE_NAME}:${TAG_FREQAI_RL} ${GHCR_IMAGE_NAME}:${TAG_FREQAI_RL} # Tag as latest for develop builds if [ "${TAG}" = "develop" ]; then @@ -103,8 +101,7 @@ if [ "${TAG}" = "develop" ]; then docker manifest create ${IMAGE_NAME}:latest ${CACHE_IMAGE}:${TAG_ARM} ${IMAGE_NAME}:${TAG_PI} ${CACHE_IMAGE}:${TAG} docker manifest push -p ${IMAGE_NAME}:latest - docker manifest create ${GHCR_IMAGE_NAME}:latest ${CACHE_IMAGE}:${TAG_ARM} ${IMAGE_NAME}:${TAG_PI} ${CACHE_IMAGE}:${TAG} - docker manifest push -p ${GHCR_IMAGE_NAME}:latest + crane copy ${IMAGE_NAME}:latest ${GHCR_IMAGE_NAME}:latest fi docker images diff --git a/build_helpers/publish_docker_multi.sh b/build_helpers/publish_docker_multi.sh index 3e5e61564..27fa06b95 100755 --- a/build_helpers/publish_docker_multi.sh +++ b/build_helpers/publish_docker_multi.sh @@ -2,6 +2,8 @@ # The below assumes a correctly setup docker buildx environment +IMAGE_NAME=freqtradeorg/freqtrade +CACHE_IMAGE=freqtradeorg/freqtrade_cache # Replace / with _ to create a valid tag TAG=$(echo "${BRANCH_NAME}" | sed -e "s/\//_/g") TAG_PLOT=${TAG}_plot @@ -11,7 +13,6 @@ TAG_PI="${TAG}_pi" PI_PLATFORM="linux/arm/v7" echo "Running for ${TAG}" -CACHE_IMAGE=freqtradeorg/freqtrade_cache CACHE_TAG=${CACHE_IMAGE}:${TAG_PI}_cache # Add commit and commit_message to docker container From 628f6b8b7cdc4c73d89d3aec678366f021761cb4 Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 15 Mar 2023 20:41:08 +0100 Subject: [PATCH 170/229] Fix crane docker permissions --- .github/workflows/ci.yml | 7 ------- build_helpers/publish_docker_arm64.sh | 7 +++++-- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f09e5feac..663cfb1be 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -493,13 +493,6 @@ jobs: run: | echo "${DOCKER_PASSWORD}" | docker login --username ${DOCKER_USERNAME} --password-stdin - # - name: GHCR.io login - # env: - # GHCR_USERNAME: ${{ github.actor }} - # GHCR_PASSWORD: ${{ secrets.GITHUB_TOKEN }} - # run: | - # echo "${GHCR_PASSWORD}" | docker login ghcr.io --username ${GHCR_USERNAME} --password-stdin - - name: Build and test and push docker images env: BRANCH_NAME: ${{ steps.extract_branch.outputs.branch }} diff --git a/build_helpers/publish_docker_arm64.sh b/build_helpers/publish_docker_arm64.sh index 3de113d37..ce0fab6ec 100755 --- a/build_helpers/publish_docker_arm64.sh +++ b/build_helpers/publish_docker_arm64.sh @@ -86,9 +86,11 @@ docker manifest push -p ${IMAGE_NAME}:${TAG_FREQAI_RL} # copy images to ghcr.io -alias crane="docker run --rm -v $(pwd)/crane:/home/nonroot/.docker/ gcr.io/go-containerregistry/crane" +alias crane="docker run --rm --i -v $(pwd)/.crane:/home/nonroot/.docker/ gcr.io/go-containerregistry/crane" +mkdir .crane +chmod a+rwx .crane -echo "${GHCR_TOKEN}" | crane auth login ghcr.io -u ${GHCR_USER} --password-stdin +echo "${GHCR_TOKEN}" | crane auth login ghcr.io -u "${GHCR_USERNAME}" --password-stdin crane copy ${IMAGE_NAME}:${TAG} ${GHCR_IMAGE_NAME}:${TAG} crane copy ${IMAGE_NAME}:${TAG_PLOT} ${GHCR_IMAGE_NAME}:${TAG_PLOT} @@ -105,6 +107,7 @@ if [ "${TAG}" = "develop" ]; then fi docker images +rm -rf .crane # Cleanup old images from arm64 node. docker image prune -a --force --filter "until=24h" From 764d5507a3914d5f109ffd98c3c21fb6e6449aa5 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 16 Mar 2023 19:33:56 +0100 Subject: [PATCH 171/229] Fix typo in docker param --- build_helpers/publish_docker_arm64.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build_helpers/publish_docker_arm64.sh b/build_helpers/publish_docker_arm64.sh index ce0fab6ec..696f5bc48 100755 --- a/build_helpers/publish_docker_arm64.sh +++ b/build_helpers/publish_docker_arm64.sh @@ -86,7 +86,7 @@ docker manifest push -p ${IMAGE_NAME}:${TAG_FREQAI_RL} # copy images to ghcr.io -alias crane="docker run --rm --i -v $(pwd)/.crane:/home/nonroot/.docker/ gcr.io/go-containerregistry/crane" +alias crane="docker run --rm -i -v $(pwd)/.crane:/home/nonroot/.docker/ gcr.io/go-containerregistry/crane" mkdir .crane chmod a+rwx .crane From 9044052b4e1eded666da0b1ad00e50fa5e7ef311 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 17 Mar 2023 06:46:55 +0100 Subject: [PATCH 172/229] Fix exceptions when training fails --- freqtrade/freqai/freqai_interface.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/freqtrade/freqai/freqai_interface.py b/freqtrade/freqai/freqai_interface.py index 884849446..07c357de3 100644 --- a/freqtrade/freqai/freqai_interface.py +++ b/freqtrade/freqai/freqai_interface.py @@ -104,6 +104,7 @@ class IFreqaiModel(ABC): self.data_provider: Optional[DataProvider] = None self.max_system_threads = max(int(psutil.cpu_count() * 2 - 2), 1) self.can_short = True # overridden in start() with strategy.can_short + self.model: Any = None record_params(config, self.full_path) @@ -338,13 +339,14 @@ class IFreqaiModel(ABC): except Exception as msg: logger.warning( f"Training {pair} raised exception {msg.__class__.__name__}. " - f"Message: {msg}, skipping.") + f"Message: {msg}, skipping.", exc_info=True) + self.model = None self.dd.pair_dict[pair]["trained_timestamp"] = int( tr_train.stopts) - if self.plot_features: + if self.plot_features and self.model is not None: plot_feature_importance(self.model, pair, dk, self.plot_features) - if self.save_backtest_models: + if self.save_backtest_models and self.model is not None: logger.info('Saving backtest model to disk.') self.dd.save_data(self.model, pair, dk) else: From 477dc504250f7e305e592664d1a30932e36cfdd8 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 18 Mar 2023 16:32:07 +0000 Subject: [PATCH 173/229] Add pair output to "tossed" messages --- freqtrade/freqai/data_kitchen.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/freqtrade/freqai/data_kitchen.py b/freqtrade/freqai/data_kitchen.py index 66923b5c2..52d487b08 100644 --- a/freqtrade/freqai/data_kitchen.py +++ b/freqtrade/freqai/data_kitchen.py @@ -251,7 +251,7 @@ class FreqaiDataKitchen: (drop_index == 0) & (drop_index_labels == 0) ] logger.info( - f"dropped {len(unfiltered_df) - len(filtered_df)} training points" + f"{self.pair}: dropped {len(unfiltered_df) - len(filtered_df)} training points" f" due to NaNs in populated dataset {len(unfiltered_df)}." ) if (1 - len(filtered_df) / len(unfiltered_df)) > 0.1 and self.live: @@ -675,7 +675,7 @@ class FreqaiDataKitchen: ] logger.info( - f"SVM tossed {len(y_pred) - kept_points.sum()}" + f"{self.pair}: SVM tossed {len(y_pred) - kept_points.sum()}" f" test points from {len(y_pred)} total points." ) @@ -949,7 +949,7 @@ class FreqaiDataKitchen: if (len(do_predict) - do_predict.sum()) > 0: logger.info( - f"DI tossed {len(do_predict) - do_predict.sum()} predictions for " + f"{self.pair}: DI tossed {len(do_predict) - do_predict.sum()} predictions for " "being too far from training data." ) From 818d2bf92afcb6d41f3c91d3b81fb045dcfd470b Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 18 Mar 2023 17:02:17 +0100 Subject: [PATCH 174/229] Fix stoploss on exchange value in /show_config call --- freqtrade/rpc/rpc.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index eb184c6d6..6b82efe71 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -123,7 +123,7 @@ class RPC: if config['max_open_trades'] != float('inf') else -1), 'minimal_roi': config['minimal_roi'].copy() if 'minimal_roi' in config else {}, 'stoploss': config.get('stoploss'), - 'stoploss_on_exchange': config.get('stoploss_on_exchange', False), + 'stoploss_on_exchange': config.get('order_types', {}).get('stoploss_on_exchange', False), 'trailing_stop': config.get('trailing_stop'), 'trailing_stop_positive': config.get('trailing_stop_positive'), 'trailing_stop_positive_offset': config.get('trailing_stop_positive_offset'), From d808dd49e81978f84a3ff40bf0cce215b40455ca Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 18 Mar 2023 19:28:13 +0100 Subject: [PATCH 175/229] Fix ruff violation --- freqtrade/rpc/rpc.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 6b82efe71..c6a6f5cae 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -123,7 +123,8 @@ class RPC: if config['max_open_trades'] != float('inf') else -1), 'minimal_roi': config['minimal_roi'].copy() if 'minimal_roi' in config else {}, 'stoploss': config.get('stoploss'), - 'stoploss_on_exchange': config.get('order_types', {}).get('stoploss_on_exchange', False), + 'stoploss_on_exchange': config.get('order_types', + {}).get('stoploss_on_exchange', False), 'trailing_stop': config.get('trailing_stop'), 'trailing_stop_positive': config.get('trailing_stop_positive'), 'trailing_stop_positive_offset': config.get('trailing_stop_positive_offset'), From b0a7b64d444ddffdb47ec11166a3126f54f2d5da Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 17 Mar 2023 20:41:11 +0100 Subject: [PATCH 176/229] Close sessions after telegram calls --- freqtrade/rpc/telegram.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/freqtrade/rpc/telegram.py b/freqtrade/rpc/telegram.py index 0c0b24f00..fda791313 100644 --- a/freqtrade/rpc/telegram.py +++ b/freqtrade/rpc/telegram.py @@ -83,6 +83,8 @@ def authorized_only(command_handler: Callable[..., None]) -> Callable[..., Any]: self._send_msg(str(e)) except BaseException: logger.exception('Exception occurred within Telegram module') + finally: + Trade.session.remove() return wrapper From 62c8dd98d57c8d0ece15ff2a31f83a68f0f2d34d Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 17 Mar 2023 20:44:00 +0100 Subject: [PATCH 177/229] Use combination of thread-local and asyncio-aware session context --- freqtrade/persistence/models.py | 25 ++++++++++++++++++++++--- freqtrade/rpc/api_server/deps.py | 15 ++++++++++++--- tests/rpc/test_rpc_telegram.py | 6 ++++-- 3 files changed, 38 insertions(+), 8 deletions(-) diff --git a/freqtrade/persistence/models.py b/freqtrade/persistence/models.py index eee07e61c..2315c0acc 100644 --- a/freqtrade/persistence/models.py +++ b/freqtrade/persistence/models.py @@ -2,7 +2,9 @@ This module contains the class to persist trades into SQLite """ import logging -from typing import Any, Dict +import threading +from contextvars import ContextVar +from typing import Any, Dict, Final, Optional from sqlalchemy import create_engine, inspect from sqlalchemy.exc import NoSuchModuleError @@ -19,6 +21,22 @@ from freqtrade.persistence.trade_model import Order, Trade logger = logging.getLogger(__name__) +REQUEST_ID_CTX_KEY: Final[str] = 'request_id' +_request_id_ctx_var: ContextVar[Optional[str]] = ContextVar(REQUEST_ID_CTX_KEY, default=None) + + +def get_request_or_thread_id() -> Optional[str]: + """ + Helper method to get either async context (for fastapi requests), or thread id + """ + id = _request_id_ctx_var.get() + if id is None: + # when not in request context - use thread id + id = str(threading.current_thread().ident) + + return id + + _SQL_DOCS_URL = 'http://docs.sqlalchemy.org/en/latest/core/engines.html#database-urls' @@ -53,8 +71,9 @@ def init_db(db_url: str) -> None: # https://docs.sqlalchemy.org/en/13/orm/contextual.html#thread-local-scope # Scoped sessions proxy requests to the appropriate thread-local session. - # We should use the scoped_session object - not a seperately initialized version - Trade.session = scoped_session(sessionmaker(bind=engine, autoflush=False)) + # Since we also use fastAPI, we need to make it aware of the request id, too + Trade.session = scoped_session(sessionmaker( + bind=engine, autoflush=False), scopefunc=get_request_or_thread_id) Order.session = Trade.session PairLock.session = Trade.session diff --git a/freqtrade/rpc/api_server/deps.py b/freqtrade/rpc/api_server/deps.py index aed97367b..eb41d728d 100644 --- a/freqtrade/rpc/api_server/deps.py +++ b/freqtrade/rpc/api_server/deps.py @@ -1,9 +1,11 @@ from typing import Any, Dict, Iterator, Optional +from uuid import uuid4 from fastapi import Depends from freqtrade.enums import RunMode from freqtrade.persistence import Trade +from freqtrade.persistence.models import _request_id_ctx_var from freqtrade.rpc.rpc import RPC, RPCException from .webserver import ApiServer @@ -15,12 +17,19 @@ def get_rpc_optional() -> Optional[RPC]: return None -def get_rpc() -> Optional[Iterator[RPC]]: +async def get_rpc() -> Optional[Iterator[RPC]]: + _rpc = get_rpc_optional() if _rpc: + request_id = str(uuid4()) + ctx_token = _request_id_ctx_var.set(request_id) Trade.rollback() - yield _rpc - Trade.rollback() + try: + yield _rpc + finally: + Trade.session.remove() + _request_id_ctx_var.reset(ctx_token) + else: raise RPCException('Bot is not in the correct state') diff --git a/tests/rpc/test_rpc_telegram.py b/tests/rpc/test_rpc_telegram.py index b1859f581..521e3b66d 100644 --- a/tests/rpc/test_rpc_telegram.py +++ b/tests/rpc/test_rpc_telegram.py @@ -674,8 +674,9 @@ def test_monthly_handle(default_conf_usdt, update, ticker, fee, mocker, time_mac assert str('Monthly Profit over the last 6 months:') in msg_mock.call_args_list[0][0][0] -def test_profit_handle(default_conf_usdt, update, ticker_usdt, ticker_sell_up, fee, - limit_sell_order_usdt, mocker) -> None: +def test_telegram_profit_handle( + default_conf_usdt, update, ticker_usdt, ticker_sell_up, fee, + limit_sell_order_usdt, mocker) -> None: mocker.patch('freqtrade.rpc.rpc.CryptoToFiatConverter._find_price', return_value=1.1) mocker.patch.multiple( EXMS, @@ -710,6 +711,7 @@ def test_profit_handle(default_conf_usdt, update, ticker_usdt, ticker_sell_up, f # Update the ticker with a market going up mocker.patch(f'{EXMS}.fetch_ticker', ticker_sell_up) # Simulate fulfilled LIMIT_SELL order for trade + trade = Trade.session.scalars(select(Trade)).first() oobj = Order.parse_from_ccxt_object( limit_sell_order_usdt, limit_sell_order_usdt['symbol'], 'sell') trade.orders.append(oobj) From b1f88e88612285c5ccaa219c6d9366a575c30de9 Mon Sep 17 00:00:00 2001 From: hippocritical Date: Sat, 18 Mar 2023 20:02:55 +0100 Subject: [PATCH 178/229] fixed typo from trades to trade --- freqtrade/strategy/strategyupdater.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/freqtrade/strategy/strategyupdater.py b/freqtrade/strategy/strategyupdater.py index bc692b71c..2669dcc4a 100644 --- a/freqtrade/strategy/strategyupdater.py +++ b/freqtrade/strategy/strategyupdater.py @@ -181,7 +181,7 @@ class NameUpdater(ast_comments.NodeTransformer): def visit_Attribute(self, node): if ( isinstance(node.value, ast_comments.Name) - and node.value.id == 'trades' + and node.value.id == 'trade' and node.attr == 'nr_of_successful_buys' ): node.attr = 'nr_of_successful_entries' From bf3f2e4de4cdaf52f41e55ef65ab997a5c29e50d Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 19 Mar 2023 11:16:54 +0100 Subject: [PATCH 179/229] Fix failing test --- tests/test_strategy_updater.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_strategy_updater.py b/tests/test_strategy_updater.py index d3bdd27b5..597d49fda 100644 --- a/tests/test_strategy_updater.py +++ b/tests/test_strategy_updater.py @@ -124,11 +124,11 @@ def test_strategy_updater_method_params(default_conf, caplog) -> None: instance_strategy_updater = StrategyUpdater() modified_code = instance_strategy_updater.update_code(""" def confirm_trade_exit(sell_reason: str): - nr_orders = trades.nr_of_successful_buys + nr_orders = trade.nr_of_successful_buys pass """) assert "exit_reason" in modified_code - assert "nr_orders = trades.nr_of_successful_entries" in modified_code + assert "nr_orders = trade.nr_of_successful_entries" in modified_code def test_strategy_updater_dicts(default_conf, caplog) -> None: From f5f151fcc54b2255e4dc167276500fd937b54f8c Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 19 Mar 2023 15:06:56 +0100 Subject: [PATCH 180/229] Fix typing error --- freqtrade/rpc/api_server/deps.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/freqtrade/rpc/api_server/deps.py b/freqtrade/rpc/api_server/deps.py index eb41d728d..f5b1bcd74 100644 --- a/freqtrade/rpc/api_server/deps.py +++ b/freqtrade/rpc/api_server/deps.py @@ -1,4 +1,4 @@ -from typing import Any, Dict, Iterator, Optional +from typing import Any, AsyncIterator, Dict, Optional from uuid import uuid4 from fastapi import Depends @@ -17,7 +17,7 @@ def get_rpc_optional() -> Optional[RPC]: return None -async def get_rpc() -> Optional[Iterator[RPC]]: +async def get_rpc() -> Optional[AsyncIterator[RPC]]: _rpc = get_rpc_optional() if _rpc: From 9ccc3e52ec0ae5da850452a6d703d47aa1a4ccba Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 19 Mar 2023 15:30:27 +0100 Subject: [PATCH 181/229] Simplify time in force code structure --- freqtrade/exchange/exchange.py | 4 +--- freqtrade/exchange/gate.py | 3 +-- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/freqtrade/exchange/exchange.py b/freqtrade/exchange/exchange.py index 489dc1b68..e5f897c2a 100644 --- a/freqtrade/exchange/exchange.py +++ b/freqtrade/exchange/exchange.py @@ -60,7 +60,6 @@ class Exchange: _ft_has_default: Dict = { "stoploss_on_exchange": False, "order_time_in_force": ["GTC"], - "time_in_force_parameter": "timeInForce", "ohlcv_params": {}, "ohlcv_candle_limit": 500, "ohlcv_has_history": True, # Some exchanges (Kraken) don't provide history via ohlcv @@ -1034,8 +1033,7 @@ class Exchange: ) -> Dict: params = self._params.copy() if time_in_force != 'GTC' and ordertype != 'market': - param = self._ft_has.get('time_in_force_parameter', '') - params.update({param: time_in_force.upper()}) + params.update({'timeInForce': time_in_force.upper()}) if reduceOnly: params.update({'reduceOnly': True}) return params diff --git a/freqtrade/exchange/gate.py b/freqtrade/exchange/gate.py index 03b568460..bf6d5b59c 100644 --- a/freqtrade/exchange/gate.py +++ b/freqtrade/exchange/gate.py @@ -75,8 +75,7 @@ class Gate(Exchange): ) if ordertype == 'market' and self.trading_mode == TradingMode.FUTURES: params['type'] = 'market' - param = self._ft_has.get('time_in_force_parameter', '') - params.update({param: 'IOC'}) + params.update({'timeInForce': 'IOC'}) return params def get_trades_for_order(self, order_id: str, pair: str, since: datetime, From 3d91dd8a982df6c2768d63178e4fcd0be590d2ce Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 19 Mar 2023 15:36:35 +0100 Subject: [PATCH 182/229] Support post-only orders for Binance spot closes #8044 --- freqtrade/exchange/binance.py | 24 +++++++++++++++++++++++- tests/exchange/test_binance.py | 13 +++++++++++++ tests/exchange/test_exchange.py | 2 +- 3 files changed, 37 insertions(+), 2 deletions(-) diff --git a/freqtrade/exchange/binance.py b/freqtrade/exchange/binance.py index 9580bc690..a89c02631 100644 --- a/freqtrade/exchange/binance.py +++ b/freqtrade/exchange/binance.py @@ -7,6 +7,7 @@ from typing import Dict, List, Optional, Tuple import arrow import ccxt +from freqtrade.constants import BuySell from freqtrade.enums import CandleType, MarginMode, PriceType, TradingMode from freqtrade.exceptions import DDosProtection, OperationalException, TemporaryError from freqtrade.exchange import Exchange @@ -23,7 +24,7 @@ class Binance(Exchange): _ft_has: Dict = { "stoploss_on_exchange": True, "stoploss_order_types": {"limit": "stop_loss_limit"}, - "order_time_in_force": ['GTC', 'FOK', 'IOC'], + "order_time_in_force": ["GTC", "FOK", "IOC", "PO"], "ohlcv_candle_limit": 1000, "trades_pagination": "id", "trades_pagination_arg": "fromId", @@ -31,6 +32,7 @@ class Binance(Exchange): } _ft_has_futures: Dict = { "stoploss_order_types": {"limit": "stop", "market": "stop_market"}, + "order_time_in_force": ["GTC", "FOK", "IOC"], "tickers_have_price": False, "floor_leverage": True, "stop_price_type_field": "workingType", @@ -47,6 +49,26 @@ class Binance(Exchange): (TradingMode.FUTURES, MarginMode.ISOLATED) ] + def _get_params( + self, + side: BuySell, + ordertype: str, + leverage: float, + reduceOnly: bool, + time_in_force: str = 'GTC', + ) -> Dict: + params = super()._get_params(side, ordertype, leverage, reduceOnly, time_in_force) + if ( + time_in_force == 'PO' + and ordertype != 'market' + and self.trading_mode == TradingMode.SPOT + # Only spot can do post only orders + ): + params.pop('timeInForce') + params['postOnly'] = True + + return params + def get_tickers(self, symbols: Optional[List[str]] = None, cached: bool = False) -> Tickers: tickers = super().get_tickers(symbols=symbols, cached=cached) if self.trading_mode == TradingMode.FUTURES: diff --git a/tests/exchange/test_binance.py b/tests/exchange/test_binance.py index 616910682..ba786bb3b 100644 --- a/tests/exchange/test_binance.py +++ b/tests/exchange/test_binance.py @@ -11,6 +11,19 @@ from tests.conftest import EXMS, get_mock_coro, get_patched_exchange, log_has_re from tests.exchange.test_exchange import ccxt_exceptionhandlers +@pytest.mark.parametrize('side,type,time_in_force,expected', [ + ('buy', 'limit', 'gtc', {'timeInForce': 'GTC'}), + ('buy', 'limit', 'IOC', {'timeInForce': 'IOC'}), + ('buy', 'market', 'IOC', {}), + ('buy', 'limit', 'PO', {'postOnly': True}), + ('sell', 'limit', 'PO', {'postOnly': True}), + ('sell', 'market', 'PO', {}), + ]) +def test__get_params_binance(default_conf, mocker, side, type, time_in_force, expected): + exchange = get_patched_exchange(mocker, default_conf, id='binance') + assert exchange._get_params(side, type, 1, False, time_in_force) == expected + + @pytest.mark.parametrize('trademode', [TradingMode.FUTURES, TradingMode.SPOT]) @pytest.mark.parametrize('limitratio,expected,side', [ (None, 220 * 0.99, "sell"), diff --git a/tests/exchange/test_exchange.py b/tests/exchange/test_exchange.py index d7f6a8b90..7c48f1c9d 100644 --- a/tests/exchange/test_exchange.py +++ b/tests/exchange/test_exchange.py @@ -3387,7 +3387,7 @@ def test_merge_ft_has_dict(default_conf, mocker): ex = Binance(default_conf) assert ex._ft_has != Exchange._ft_has_default assert ex.get_option('stoploss_on_exchange') - assert ex.get_option('order_time_in_force') == ['GTC', 'FOK', 'IOC'] + assert ex.get_option('order_time_in_force') == ['GTC', 'FOK', 'IOC', 'PO'] assert ex.get_option('trades_pagination') == 'id' assert ex.get_option('trades_pagination_arg') == 'fromId' From 236499a195d61bb2f3e54917a42b4a37af612ea5 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 19 Mar 2023 15:47:42 +0100 Subject: [PATCH 183/229] Reorder push logic for ghcr --- build_helpers/publish_docker_arm64.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/build_helpers/publish_docker_arm64.sh b/build_helpers/publish_docker_arm64.sh index 696f5bc48..a6ecdbee6 100755 --- a/build_helpers/publish_docker_arm64.sh +++ b/build_helpers/publish_docker_arm64.sh @@ -92,10 +92,10 @@ chmod a+rwx .crane echo "${GHCR_TOKEN}" | crane auth login ghcr.io -u "${GHCR_USERNAME}" --password-stdin -crane copy ${IMAGE_NAME}:${TAG} ${GHCR_IMAGE_NAME}:${TAG} -crane copy ${IMAGE_NAME}:${TAG_PLOT} ${GHCR_IMAGE_NAME}:${TAG_PLOT} -crane copy ${IMAGE_NAME}:${TAG_FREQAI} ${GHCR_IMAGE_NAME}:${TAG_FREQAI} crane copy ${IMAGE_NAME}:${TAG_FREQAI_RL} ${GHCR_IMAGE_NAME}:${TAG_FREQAI_RL} +crane copy ${IMAGE_NAME}:${TAG_FREQAI} ${GHCR_IMAGE_NAME}:${TAG_FREQAI} +crane copy ${IMAGE_NAME}:${TAG_PLOT} ${GHCR_IMAGE_NAME}:${TAG_PLOT} +crane copy ${IMAGE_NAME}:${TAG} ${GHCR_IMAGE_NAME}:${TAG} # Tag as latest for develop builds if [ "${TAG}" = "develop" ]; then From 222ecdecd29120e07ae1b8dcebea0e6525206b77 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 19 Mar 2023 17:50:08 +0100 Subject: [PATCH 184/229] Improve code quality --- freqtrade/commands/analyze_commands.py | 4 ++-- freqtrade/optimize/hyperopt_tools.py | 3 +-- freqtrade/rpc/telegram.py | 4 ++-- freqtrade/rpc/webhook.py | 2 +- tests/data/test_btanalysis.py | 2 +- tests/data/test_history.py | 2 +- tests/optimize/test_optimize_reports.py | 4 ++-- tests/rpc/test_rpc_telegram.py | 8 ++++---- tests/strategy/test_strategy_loading.py | 2 +- 9 files changed, 15 insertions(+), 16 deletions(-) diff --git a/freqtrade/commands/analyze_commands.py b/freqtrade/commands/analyze_commands.py index 20afa7ffd..e928ccad7 100644 --- a/freqtrade/commands/analyze_commands.py +++ b/freqtrade/commands/analyze_commands.py @@ -40,8 +40,8 @@ def setup_analyze_configuration(args: Dict[str, Any], method: RunMode) -> Dict[s if (not Path(signals_file).exists()): raise OperationalException( - (f"Cannot find latest backtest signals file: {signals_file}." - "Run backtesting with `--export signals`.") + f"Cannot find latest backtest signals file: {signals_file}." + "Run backtesting with `--export signals`." ) return config diff --git a/freqtrade/optimize/hyperopt_tools.py b/freqtrade/optimize/hyperopt_tools.py index cf0650f7d..93efbf644 100644 --- a/freqtrade/optimize/hyperopt_tools.py +++ b/freqtrade/optimize/hyperopt_tools.py @@ -1,4 +1,3 @@ -import io import logging from copy import deepcopy from datetime import datetime, timezone @@ -464,7 +463,7 @@ class HyperoptTools(): return try: - io.open(csv_file, 'w+').close() + Path(csv_file).open('w+').close() except IOError: logger.error(f"Failed to create CSV file: {csv_file}") return diff --git a/freqtrade/rpc/telegram.py b/freqtrade/rpc/telegram.py index 0c0b24f00..cb219eef1 100644 --- a/freqtrade/rpc/telegram.py +++ b/freqtrade/rpc/telegram.py @@ -1340,7 +1340,7 @@ class Telegram(RPCHandler): message = tabulate({k: [v] for k, v in counts.items()}, headers=['current', 'max', 'total stake'], tablefmt='simple') - message = "
{}
".format(message) + message = f"
{message}
" logger.debug(message) self._send_msg(message, parse_mode=ParseMode.HTML, reload_able=True, callback_path="update_count", @@ -1642,7 +1642,7 @@ class Telegram(RPCHandler): ]) else: reply_markup = InlineKeyboardMarkup([[]]) - msg += "\nUpdated: {}".format(datetime.now().ctime()) + msg += f"\nUpdated: {datetime.now().ctime()}" if not query.message: return chat_id = query.message.chat_id diff --git a/freqtrade/rpc/webhook.py b/freqtrade/rpc/webhook.py index 0967de70d..118ebed88 100644 --- a/freqtrade/rpc/webhook.py +++ b/freqtrade/rpc/webhook.py @@ -113,7 +113,7 @@ class Webhook(RPCHandler): response = post(self._url, data=payload['data'], headers={'Content-Type': 'text/plain'}) else: - raise NotImplementedError('Unknown format: {}'.format(self._format)) + raise NotImplementedError(f'Unknown format: {self._format}') # Throw a RequestException if the post was not successful response.raise_for_status() diff --git a/tests/data/test_btanalysis.py b/tests/data/test_btanalysis.py index 345e3c299..2c5515f7c 100644 --- a/tests/data/test_btanalysis.py +++ b/tests/data/test_btanalysis.py @@ -98,7 +98,7 @@ def test_load_backtest_data_new_format(testdatadir): assert bt_data.equals(bt_data3) with pytest.raises(ValueError, match=r"File .* does not exist\."): - load_backtest_data(str("filename") + "nofile") + load_backtest_data("filename" + "nofile") with pytest.raises(ValueError, match=r"Unknown dataformat."): load_backtest_data(testdatadir / "backtest_results" / LAST_BT_RESULT_FN) diff --git a/tests/data/test_history.py b/tests/data/test_history.py index c967f0c89..24ad8bcc9 100644 --- a/tests/data/test_history.py +++ b/tests/data/test_history.py @@ -409,7 +409,7 @@ def test_init_with_refresh(default_conf, mocker) -> None: def test_file_dump_json_tofile(testdatadir) -> None: - file = testdatadir / 'test_{id}.json'.format(id=str(uuid.uuid4())) + file = testdatadir / f'test_{uuid.uuid4()}.json' data = {'bar': 'foo'} # check the file we will create does not exist diff --git a/tests/optimize/test_optimize_reports.py b/tests/optimize/test_optimize_reports.py index f71e6c492..0cc32baaf 100644 --- a/tests/optimize/test_optimize_reports.py +++ b/tests/optimize/test_optimize_reports.py @@ -236,7 +236,7 @@ def test_store_backtest_candles(testdatadir, mocker): assert dump_mock.call_count == 1 assert isinstance(dump_mock.call_args_list[0][0][0], Path) - assert str(dump_mock.call_args_list[0][0][0]).endswith(str('_signals.pkl')) + assert str(dump_mock.call_args_list[0][0][0]).endswith('_signals.pkl') dump_mock.reset_mock() # mock file exporting @@ -245,7 +245,7 @@ def test_store_backtest_candles(testdatadir, mocker): assert dump_mock.call_count == 1 assert isinstance(dump_mock.call_args_list[0][0][0], Path) # result will be testdatadir / testresult-_signals.pkl - assert str(dump_mock.call_args_list[0][0][0]).endswith(str('_signals.pkl')) + assert str(dump_mock.call_args_list[0][0][0]).endswith('_signals.pkl') dump_mock.reset_mock() diff --git a/tests/rpc/test_rpc_telegram.py b/tests/rpc/test_rpc_telegram.py index b1859f581..7dabe9dfe 100644 --- a/tests/rpc/test_rpc_telegram.py +++ b/tests/rpc/test_rpc_telegram.py @@ -652,7 +652,7 @@ def test_monthly_handle(default_conf_usdt, update, ticker, fee, mocker, time_mac # The one-digit months should contain a zero, Eg: September 2021 = "2021-09" # Since we loaded the last 12 months, any month should appear - assert str('-09') in msg_mock.call_args_list[0][0][0] + assert '-09' in msg_mock.call_args_list[0][0][0] # Try invalid data msg_mock.reset_mock() @@ -671,7 +671,7 @@ def test_monthly_handle(default_conf_usdt, update, ticker, fee, mocker, time_mac context = MagicMock() context.args = ["february"] telegram._monthly(update=update, context=context) - assert str('Monthly Profit over the last 6 months:') in msg_mock.call_args_list[0][0][0] + assert 'Monthly Profit over the last 6 months:' in msg_mock.call_args_list[0][0][0] def test_profit_handle(default_conf_usdt, update, ticker_usdt, ticker_sell_up, fee, @@ -1730,14 +1730,14 @@ def test_version_handle(default_conf, update, mocker) -> None: telegram._version(update=update, context=MagicMock()) assert msg_mock.call_count == 1 - assert '*Version:* `{}`'.format(__version__) in msg_mock.call_args_list[0][0][0] + assert f'*Version:* `{__version__}`' in msg_mock.call_args_list[0][0][0] msg_mock.reset_mock() freqtradebot.strategy.version = lambda: '1.1.1' telegram._version(update=update, context=MagicMock()) assert msg_mock.call_count == 1 - assert '*Version:* `{}`'.format(__version__) in msg_mock.call_args_list[0][0][0] + assert f'*Version:* `{__version__}`' in msg_mock.call_args_list[0][0][0] assert '*Strategy version: * `1.1.1`' in msg_mock.call_args_list[0][0][0] diff --git a/tests/strategy/test_strategy_loading.py b/tests/strategy/test_strategy_loading.py index 98185e152..4cdb35936 100644 --- a/tests/strategy/test_strategy_loading.py +++ b/tests/strategy/test_strategy_loading.py @@ -69,7 +69,7 @@ def test_load_strategy(default_conf, dataframe_1m): def test_load_strategy_base64(dataframe_1m, caplog, default_conf): filepath = Path(__file__).parents[2] / 'freqtrade/templates/sample_strategy.py' encoded_string = urlsafe_b64encode(filepath.read_bytes()).decode("utf-8") - default_conf.update({'strategy': 'SampleStrategy:{}'.format(encoded_string)}) + default_conf.update({'strategy': f'SampleStrategy:{encoded_string}'}) strategy = StrategyResolver.load_strategy(default_conf) assert 'rsi' in strategy.advise_indicators(dataframe_1m, {'pair': 'ETH/BTC'}) From c92f28bf6f6e04dee47615d7022da3e901332a2b Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 19 Mar 2023 17:57:56 +0100 Subject: [PATCH 185/229] ruff: Activate UP ruleset --- freqtrade/configuration/config_validation.py | 5 +---- freqtrade/freqai/RL/TensorboardCallback.py | 2 +- freqtrade/optimize/hyperopt_tools.py | 2 +- freqtrade/vendor/qtpylib/indicators.py | 8 -------- pyproject.toml | 8 ++++++-- 5 files changed, 9 insertions(+), 16 deletions(-) diff --git a/freqtrade/configuration/config_validation.py b/freqtrade/configuration/config_validation.py index 606f081ef..0ee48cf91 100644 --- a/freqtrade/configuration/config_validation.py +++ b/freqtrade/configuration/config_validation.py @@ -27,10 +27,7 @@ def _extend_validator(validator_class): if 'default' in subschema: instance.setdefault(prop, subschema['default']) - for error in validate_properties( - validator, properties, instance, schema, - ): - yield error + yield from validate_properties(validator, properties, instance, schema) return validators.extend( validator_class, {'properties': set_defaults} diff --git a/freqtrade/freqai/RL/TensorboardCallback.py b/freqtrade/freqai/RL/TensorboardCallback.py index 1828319cd..7f8c76956 100644 --- a/freqtrade/freqai/RL/TensorboardCallback.py +++ b/freqtrade/freqai/RL/TensorboardCallback.py @@ -13,7 +13,7 @@ class TensorboardCallback(BaseCallback): episodic summary reports. """ def __init__(self, verbose=1, actions: Type[Enum] = BaseActions): - super(TensorboardCallback, self).__init__(verbose) + super().__init__(verbose) self.model: Any = None self.logger = None # type: Any self.training_env: BaseEnvironment = None # type: ignore diff --git a/freqtrade/optimize/hyperopt_tools.py b/freqtrade/optimize/hyperopt_tools.py index 93efbf644..e2133a956 100644 --- a/freqtrade/optimize/hyperopt_tools.py +++ b/freqtrade/optimize/hyperopt_tools.py @@ -464,7 +464,7 @@ class HyperoptTools(): try: Path(csv_file).open('w+').close() - except IOError: + except OSError: logger.error(f"Failed to create CSV file: {csv_file}") return diff --git a/freqtrade/vendor/qtpylib/indicators.py b/freqtrade/vendor/qtpylib/indicators.py index 3da4f038d..63797d462 100644 --- a/freqtrade/vendor/qtpylib/indicators.py +++ b/freqtrade/vendor/qtpylib/indicators.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- -# # QTPyLib: Quantitative Trading Python Library # https://github.com/ranaroussi/qtpylib # @@ -18,7 +16,6 @@ # limitations under the License. # -import sys import warnings from datetime import datetime, timedelta @@ -27,11 +24,6 @@ import pandas as pd from pandas.core.base import PandasObject -# ============================================= -# check min, python version -if sys.version_info < (3, 4): - raise SystemError("QTPyLib requires Python version >= 3.4") - # ============================================= warnings.simplefilter(action="ignore", category=RuntimeWarning) diff --git a/pyproject.toml b/pyproject.toml index 71687961d..81ab50d40 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -68,15 +68,19 @@ target-version = "py38" extend-select = [ "C90", # mccabe # "N", # pep8-naming - # "UP", # pyupgrade + "UP", # pyupgrade "TID", # flake8-tidy-imports # "EXE", # flake8-executable "YTT", # flake8-2020 + # "S", # flake8-bandit # "DTZ", # flake8-datetimez # "RSE", # flake8-raise # "TCH", # flake8-type-checking - "PTH", # flake8-use-pathlib + "PTH", # flake8-use-pathlib ] [tool.ruff.mccabe] max-complexity = 12 + +[tool.ruff.per-file-ignores] +"tests/*" = ["S"] From ce3efa8f00aac5fe7c733271cdcf3c27e0ab0d09 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 19 Mar 2023 18:05:08 +0100 Subject: [PATCH 186/229] Remove pointless asserts --- freqtrade/optimize/backtesting.py | 4 ---- pyproject.toml | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/freqtrade/optimize/backtesting.py b/freqtrade/optimize/backtesting.py index 5e1e9b48a..315b3b9db 100644 --- a/freqtrade/optimize/backtesting.py +++ b/freqtrade/optimize/backtesting.py @@ -442,10 +442,6 @@ class Backtesting: # Worst case: price ticks tiny bit above open and dives down. stop_rate = row[OPEN_IDX] * (1 - side_1 * abs( (trade.stop_loss_pct or 0.0) / leverage)) - if is_short: - assert stop_rate > row[LOW_IDX] - else: - assert stop_rate < row[HIGH_IDX] # Limit lower-end to candle low to avoid exits below the low. # This still remains "worst case" - but "worst realistic case". diff --git a/pyproject.toml b/pyproject.toml index 81ab50d40..c3ca9e1b0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -68,7 +68,7 @@ target-version = "py38" extend-select = [ "C90", # mccabe # "N", # pep8-naming - "UP", # pyupgrade + "UP", # pyupgrade "TID", # flake8-tidy-imports # "EXE", # flake8-executable "YTT", # flake8-2020 From a2ce288241b8a77523b9608c1418fb306a8d95c0 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 7 Jun 2022 21:05:15 +0200 Subject: [PATCH 187/229] Add okx stoploss on exchange (non-working for futures). --- freqtrade/exchange/exchange.py | 1 + freqtrade/exchange/okx.py | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/freqtrade/exchange/exchange.py b/freqtrade/exchange/exchange.py index e5f897c2a..728e997f1 100644 --- a/freqtrade/exchange/exchange.py +++ b/freqtrade/exchange/exchange.py @@ -1193,6 +1193,7 @@ class Exchange: try: params = self._get_stop_params(side=side, ordertype=ordertype, stop_price=stop_price_norm) + # TODO: reduceOnly is invalid for OKX stop orders if self.trading_mode == TradingMode.FUTURES: params['reduceOnly'] = True if 'stoploss_price_type' in order_types and 'stop_price_type_field' in self._ft_has: diff --git a/freqtrade/exchange/okx.py b/freqtrade/exchange/okx.py index e7d658d24..048d4cad5 100644 --- a/freqtrade/exchange/okx.py +++ b/freqtrade/exchange/okx.py @@ -24,6 +24,8 @@ class Okx(Exchange): "ohlcv_candle_limit": 100, # Warning, special case with data prior to X months "mark_ohlcv_timeframe": "4h", "funding_fee_timeframe": "8h", + "stoploss_order_types": {"limit": "limit"}, + "stoploss_on_exchange": True, } _ft_has_futures: Dict = { "tickers_have_quoteVolume": False, @@ -157,3 +159,26 @@ class Okx(Exchange): pair_tiers = self._leverage_tiers[pair] return pair_tiers[-1]['maxNotional'] / leverage + + def _get_stop_params(self, side: BuySell, ordertype: str, stop_price: float) -> Dict: + + params = super()._get_stop_params(side, ordertype, stop_price) + if self.trading_mode == TradingMode.FUTURES and self.margin_mode: + params['tdMode'] = self.margin_mode.value + params['posSide'] = self._get_posSide(side, True) + return params + + def fetch_stoploss_order(self, order_id: str, pair: str, params: Dict = {}) -> Dict: + # TODO: This does not work until the algo-order is actually triggered! + return self.fetch_order( + order_id=order_id, + pair=pair, + params={'stop': True} + ) + + def cancel_stoploss_order(self, order_id: str, pair: str, params: Dict = {}) -> Dict: + return self.cancel_order( + order_id=order_id, + pair=pair, + params={'stop': True} + ) From df20757d2116a52265edfbe4624ed545eddb9a23 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 8 Nov 2022 19:58:39 +0100 Subject: [PATCH 188/229] OKX stop: implement proper stoploss fetching --- freqtrade/exchange/okx.py | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/freqtrade/exchange/okx.py b/freqtrade/exchange/okx.py index 048d4cad5..8199bd0ea 100644 --- a/freqtrade/exchange/okx.py +++ b/freqtrade/exchange/okx.py @@ -6,7 +6,8 @@ import ccxt from freqtrade.constants import BuySell from freqtrade.enums import CandleType, MarginMode, TradingMode from freqtrade.enums.pricetype import PriceType -from freqtrade.exceptions import DDosProtection, OperationalException, TemporaryError +from freqtrade.exceptions import (DDosProtection, OperationalException, RetryableOrderError, + TemporaryError) from freqtrade.exchange import Exchange, date_minus_candles from freqtrade.exchange.common import retrier @@ -169,12 +170,23 @@ class Okx(Exchange): return params def fetch_stoploss_order(self, order_id: str, pair: str, params: Dict = {}) -> Dict: - # TODO: This does not work until the algo-order is actually triggered! - return self.fetch_order( - order_id=order_id, - pair=pair, - params={'stop': True} - ) + params1 = {'stop': True, 'ordType': 'trigger'} + for method in (self._api.fetch_open_orders, self._api.fetch_closed_orders, + self._api.fetch_canceled_orders): + try: + orders = method(pair, params=params1) + orders_f = [order for order in orders if order['id'] == order_id] + if orders_f: + order = orders_f[0] + if (order['status'] == 'closed' + and order.get('info', {}).get('ordId') is not None): + # Once a order triggered, we fetch the regular followup order. + return self.fetch_order(order['info']['ordId'], pair) + return order + except ccxt.BaseError: + logger.exception() + raise RetryableOrderError( + f'StoplossOrder not found (pair: {pair} id: {order_id}).') def cancel_stoploss_order(self, order_id: str, pair: str, params: Dict = {}) -> Dict: return self.cancel_order( From 6c5dc7e0a9b8643dca66e0b1df79696a3eb7cd90 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 8 Nov 2022 20:24:26 +0100 Subject: [PATCH 189/229] OKX: improve stop order handling --- freqtrade/exchange/okx.py | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/freqtrade/exchange/okx.py b/freqtrade/exchange/okx.py index 8199bd0ea..4ff7f283b 100644 --- a/freqtrade/exchange/okx.py +++ b/freqtrade/exchange/okx.py @@ -1,5 +1,5 @@ import logging -from typing import Dict, List, Optional, Tuple +from typing import Any, Dict, List, Optional, Tuple import ccxt @@ -10,6 +10,7 @@ from freqtrade.exceptions import (DDosProtection, OperationalException, Retryabl TemporaryError) from freqtrade.exchange import Exchange, date_minus_candles from freqtrade.exchange.common import retrier +from freqtrade.misc import safe_value_fallback2 logger = logging.getLogger(__name__) @@ -179,15 +180,26 @@ class Okx(Exchange): if orders_f: order = orders_f[0] if (order['status'] == 'closed' - and order.get('info', {}).get('ordId') is not None): + and (real_order_id := order.get('info', {}).get('ordId')) is not None): # Once a order triggered, we fetch the regular followup order. - return self.fetch_order(order['info']['ordId'], pair) + order_reg = self.fetch_order(real_order_id, pair) + self._log_exchange_response('fetch_stoploss_order1', order_reg) + order_reg['id_stop'] = order_reg['id'] + order_reg['id'] = order_id + order_reg['type'] = 'stop' + order_reg['status_stop'] = 'triggered' + return order_reg return order except ccxt.BaseError: logger.exception() raise RetryableOrderError( f'StoplossOrder not found (pair: {pair} id: {order_id}).') + def get_order_id_conditional(self, order: Dict[str, Any]) -> str: + if order['type'] == 'stop': + return safe_value_fallback2(order, order, 'id_stop', 'id') + return order['id'] + def cancel_stoploss_order(self, order_id: str, pair: str, params: Dict = {}) -> Dict: return self.cancel_order( order_id=order_id, From d84ece7258a0082628f4459c278851fcac7374c9 Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 9 Nov 2022 20:17:10 +0100 Subject: [PATCH 190/229] Use conditional orders for stop orders --- freqtrade/exchange/okx.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/freqtrade/exchange/okx.py b/freqtrade/exchange/okx.py index 4ff7f283b..5acf039cb 100644 --- a/freqtrade/exchange/okx.py +++ b/freqtrade/exchange/okx.py @@ -164,14 +164,17 @@ class Okx(Exchange): def _get_stop_params(self, side: BuySell, ordertype: str, stop_price: float) -> Dict: - params = super()._get_stop_params(side, ordertype, stop_price) + params = self._params.copy() + # Verify if stopPrice works for your exchange! + params.update({'stopLossPrice': stop_price}) + if self.trading_mode == TradingMode.FUTURES and self.margin_mode: params['tdMode'] = self.margin_mode.value params['posSide'] = self._get_posSide(side, True) return params def fetch_stoploss_order(self, order_id: str, pair: str, params: Dict = {}) -> Dict: - params1 = {'stop': True, 'ordType': 'trigger'} + params1 = {'stop': True, 'ordType': 'conditional'} for method in (self._api.fetch_open_orders, self._api.fetch_closed_orders, self._api.fetch_canceled_orders): try: @@ -204,5 +207,5 @@ class Okx(Exchange): return self.cancel_order( order_id=order_id, pair=pair, - params={'stop': True} + params={'ordType': 'conditional'} ) From 224f289ec8fc6d91ee32e2a3d90f4749d4da9ca0 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 12 Mar 2023 15:19:56 +0100 Subject: [PATCH 191/229] OKX Stop: Add some more okx specific logic --- freqtrade/exchange/exchange.py | 1 - freqtrade/exchange/okx.py | 31 +++++++++++++++++++++++++++++-- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/freqtrade/exchange/exchange.py b/freqtrade/exchange/exchange.py index 728e997f1..e5f897c2a 100644 --- a/freqtrade/exchange/exchange.py +++ b/freqtrade/exchange/exchange.py @@ -1193,7 +1193,6 @@ class Exchange: try: params = self._get_stop_params(side=side, ordertype=ordertype, stop_price=stop_price_norm) - # TODO: reduceOnly is invalid for OKX stop orders if self.trading_mode == TradingMode.FUTURES: params['reduceOnly'] = True if 'stoploss_price_type' in order_types and 'stop_price_type_field' in self._ft_has: diff --git a/freqtrade/exchange/okx.py b/freqtrade/exchange/okx.py index 5acf039cb..5acfe7fcc 100644 --- a/freqtrade/exchange/okx.py +++ b/freqtrade/exchange/okx.py @@ -173,7 +173,30 @@ class Okx(Exchange): params['posSide'] = self._get_posSide(side, True) return params + def stoploss_adjust(self, stop_loss: float, order: Dict, side: str) -> bool: + """ + OKX uses non-default stoploss price naming. + """ + if not self._ft_has.get('stoploss_on_exchange'): + raise OperationalException(f"stoploss is not implemented for {self.name}.") + + return ( + order.get('stopLossPrice', None) is None + or ((side == "sell" and stop_loss > float(order['stopLossPrice'])) or + (side == "buy" and stop_loss < float(order['stopLossPrice']))) + ) + def fetch_stoploss_order(self, order_id: str, pair: str, params: Dict = {}) -> Dict: + if self._config['dry_run']: + return self.fetch_dry_run_order(order_id) + + try: + params1 = {'stop': True} + order_reg = self._api.fetch_order(order_id, pair, params=params1) + self._log_exchange_response('fetch_stoploss_order1', order_reg) + return order_reg + except ccxt.OrderNotFound: + pass params1 = {'stop': True, 'ordType': 'conditional'} for method in (self._api.fetch_open_orders, self._api.fetch_closed_orders, self._api.fetch_canceled_orders): @@ -192,9 +215,10 @@ class Okx(Exchange): order_reg['type'] = 'stop' order_reg['status_stop'] = 'triggered' return order_reg + order['type'] = 'stoploss' return order except ccxt.BaseError: - logger.exception() + pass raise RetryableOrderError( f'StoplossOrder not found (pair: {pair} id: {order_id}).') @@ -204,8 +228,11 @@ class Okx(Exchange): return order['id'] def cancel_stoploss_order(self, order_id: str, pair: str, params: Dict = {}) -> Dict: + params1 = {'stop': True} + # 'ordType': 'conditional' + # return self.cancel_order( order_id=order_id, pair=pair, - params={'ordType': 'conditional'} + params=params1, ) From a7c7f720c0791d3ea2cdd5655626a8eab827813c Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 19 Mar 2023 20:03:34 +0100 Subject: [PATCH 192/229] Add test for okx fetch_stop --- freqtrade/exchange/okx.py | 2 +- tests/exchange/test_okx.py | 54 +++++++++++++++++++++++++++++++++++++- 2 files changed, 54 insertions(+), 2 deletions(-) diff --git a/freqtrade/exchange/okx.py b/freqtrade/exchange/okx.py index 5acfe7fcc..7de110acf 100644 --- a/freqtrade/exchange/okx.py +++ b/freqtrade/exchange/okx.py @@ -212,7 +212,7 @@ class Okx(Exchange): self._log_exchange_response('fetch_stoploss_order1', order_reg) order_reg['id_stop'] = order_reg['id'] order_reg['id'] = order_id - order_reg['type'] = 'stop' + order_reg['type'] = 'stoploss' order_reg['status_stop'] = 'triggered' return order_reg order['type'] = 'stoploss' diff --git a/tests/exchange/test_okx.py b/tests/exchange/test_okx.py index fce77f4c7..30e23619b 100644 --- a/tests/exchange/test_okx.py +++ b/tests/exchange/test_okx.py @@ -2,11 +2,13 @@ from datetime import datetime, timedelta, timezone from pathlib import Path from unittest.mock import MagicMock, PropertyMock +import ccxt import pytest from freqtrade.enums import CandleType, MarginMode, TradingMode +from freqtrade.exceptions import RetryableOrderError from freqtrade.exchange.exchange import timeframe_to_minutes -from tests.conftest import get_mock_coro, get_patched_exchange, log_has +from tests.conftest import EXMS, get_mock_coro, get_patched_exchange, log_has from tests.exchange.test_exchange import ccxt_exceptionhandlers @@ -476,3 +478,53 @@ def test_load_leverage_tiers_okx(default_conf, mocker, markets, tmpdir, caplog, exchange.load_leverage_tiers() assert log_has(logmsg, caplog) + + +@pytest.mark.usefixtures("init_persistence") +def test_fetch_stoploss_order_okx(default_conf, mocker): + default_conf['dry_run'] = False + api_mock = MagicMock() + api_mock.fetch_order = MagicMock() + + exchange = get_patched_exchange(mocker, default_conf, api_mock, id='okx') + + exchange.fetch_stoploss_order('1234', 'ETH/BTC') + assert api_mock.fetch_order.call_count == 1 + assert api_mock.fetch_order.call_args_list[0][0][0] == '1234' + assert api_mock.fetch_order.call_args_list[0][0][1] == 'ETH/BTC' + assert api_mock.fetch_order.call_args_list[0][1]['params'] == {'stop': True} + + api_mock.fetch_order = MagicMock(side_effect=ccxt.OrderNotFound) + api_mock.fetch_open_orders = MagicMock(return_value=[]) + api_mock.fetch_closed_orders = MagicMock(return_value=[]) + api_mock.fetch_canceled_orders = MagicMock(creturn_value=[]) + + with pytest.raises(RetryableOrderError): + exchange.fetch_stoploss_order('1234', 'ETH/BTC') + assert api_mock.fetch_order.call_count == 1 + assert api_mock.fetch_open_orders.call_count == 1 + assert api_mock.fetch_closed_orders.call_count == 1 + assert api_mock.fetch_canceled_orders.call_count == 1 + + api_mock.fetch_order.reset_mock() + api_mock.fetch_open_orders.reset_mock() + api_mock.fetch_closed_orders.reset_mock() + api_mock.fetch_canceled_orders.reset_mock() + + api_mock.fetch_closed_orders = MagicMock(return_value=[ + { + 'id': '1234', + 'status': 'closed', + 'info': {'ordId': '123455'} + } + ]) + mocker.patch(f"{EXMS}.fetch_order", MagicMock(return_value={'id': '123455'})) + resp = exchange.fetch_stoploss_order('1234', 'ETH/BTC') + assert api_mock.fetch_order.call_count == 1 + assert api_mock.fetch_open_orders.call_count == 1 + assert api_mock.fetch_closed_orders.call_count == 1 + assert api_mock.fetch_canceled_orders.call_count == 0 + + assert resp['id'] == '1234' + assert resp['id_stop'] == '123455' + assert resp['type'] == 'stoploss' From fb0e824a83fb953b4d6d61a215df72e1cd6b74b9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 20 Mar 2023 03:56:45 +0000 Subject: [PATCH 193/229] Bump nbconvert from 7.2.9 to 7.2.10 Bumps [nbconvert](https://github.com/jupyter/nbconvert) from 7.2.9 to 7.2.10. - [Release notes](https://github.com/jupyter/nbconvert/releases) - [Changelog](https://github.com/jupyter/nbconvert/blob/main/CHANGELOG.md) - [Commits](https://github.com/jupyter/nbconvert/compare/v7.2.9...v7.2.10) --- updated-dependencies: - dependency-name: nbconvert dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 6d076777f..0bdb6702e 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -22,7 +22,7 @@ time-machine==2.9.0 httpx==0.23.3 # Convert jupyter notebooks to markdown documents -nbconvert==7.2.9 +nbconvert==7.2.10 # mypy types types-cachetools==5.3.0.4 From 5ade5777e8cbef0619c3d5b33041401b082be93a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 20 Mar 2023 03:56:49 +0000 Subject: [PATCH 194/229] Bump filelock from 3.9.0 to 3.10.0 Bumps [filelock](https://github.com/tox-dev/py-filelock) from 3.9.0 to 3.10.0. - [Release notes](https://github.com/tox-dev/py-filelock/releases) - [Changelog](https://github.com/tox-dev/py-filelock/blob/main/docs/changelog.rst) - [Commits](https://github.com/tox-dev/py-filelock/compare/3.9.0...3.10.0) --- updated-dependencies: - dependency-name: filelock dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- requirements-hyperopt.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-hyperopt.txt b/requirements-hyperopt.txt index 904b5d661..4d86da2b6 100644 --- a/requirements-hyperopt.txt +++ b/requirements-hyperopt.txt @@ -5,5 +5,5 @@ scipy==1.10.1 scikit-learn==1.1.3 scikit-optimize==0.9.0 -filelock==3.9.0 +filelock==3.10.0 progressbar2==4.2.0 From 47e84ad106a34e3049a8a5412d2fb7155cff5a44 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 20 Mar 2023 03:56:54 +0000 Subject: [PATCH 195/229] Bump python-rapidjson from 1.9 to 1.10 Bumps [python-rapidjson](https://github.com/python-rapidjson/python-rapidjson) from 1.9 to 1.10. - [Release notes](https://github.com/python-rapidjson/python-rapidjson/releases) - [Changelog](https://github.com/python-rapidjson/python-rapidjson/blob/master/CHANGES.rst) - [Commits](https://github.com/python-rapidjson/python-rapidjson/compare/v1.9...v1.10) --- updated-dependencies: - dependency-name: python-rapidjson dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 9e17424f5..311285217 100644 --- a/requirements.txt +++ b/requirements.txt @@ -26,7 +26,7 @@ pyarrow==11.0.0; platform_machine != 'armv7l' py_find_1st==1.1.5 # Load ticker files 30% faster -python-rapidjson==1.9 +python-rapidjson==1.10 # Properly format api responses orjson==3.8.7 From a43502093dc18897ba4dfd2110cb5b556f1a3482 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 20 Mar 2023 03:57:07 +0000 Subject: [PATCH 196/229] Bump sqlalchemy from 2.0.5.post1 to 2.0.7 Bumps [sqlalchemy](https://github.com/sqlalchemy/sqlalchemy) from 2.0.5.post1 to 2.0.7. - [Release notes](https://github.com/sqlalchemy/sqlalchemy/releases) - [Changelog](https://github.com/sqlalchemy/sqlalchemy/blob/main/CHANGES.rst) - [Commits](https://github.com/sqlalchemy/sqlalchemy/commits) --- updated-dependencies: - dependency-name: sqlalchemy dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 9e17424f5..36861d029 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,7 +5,7 @@ pandas-ta==0.3.14b ccxt==2.9.12 cryptography==39.0.2 aiohttp==3.8.4 -SQLAlchemy==2.0.5.post1 +SQLAlchemy==2.0.7 python-telegram-bot==13.15 arrow==1.2.3 cachetools==4.2.2 From 7d1559f319ae3987fa155e6b85cd1224f11e452c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 20 Mar 2023 03:57:13 +0000 Subject: [PATCH 197/229] Bump mkdocs-material from 9.1.2 to 9.1.3 Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 9.1.2 to 9.1.3. - [Release notes](https://github.com/squidfunk/mkdocs-material/releases) - [Changelog](https://github.com/squidfunk/mkdocs-material/blob/master/CHANGELOG) - [Commits](https://github.com/squidfunk/mkdocs-material/compare/9.1.2...9.1.3) --- updated-dependencies: - dependency-name: mkdocs-material dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- docs/requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/requirements-docs.txt b/docs/requirements-docs.txt index d384a7ec5..110373844 100644 --- a/docs/requirements-docs.txt +++ b/docs/requirements-docs.txt @@ -1,6 +1,6 @@ markdown==3.3.7 mkdocs==1.4.2 -mkdocs-material==9.1.2 +mkdocs-material==9.1.3 mdx_truly_sane_lists==1.3 pymdown-extensions==9.10 jinja2==3.1.2 From fc7c8cce3cbfea9c905ecc8a503011031f7839c4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 20 Mar 2023 03:57:28 +0000 Subject: [PATCH 198/229] Bump uvicorn from 0.21.0 to 0.21.1 Bumps [uvicorn](https://github.com/encode/uvicorn) from 0.21.0 to 0.21.1. - [Release notes](https://github.com/encode/uvicorn/releases) - [Changelog](https://github.com/encode/uvicorn/blob/master/CHANGELOG.md) - [Commits](https://github.com/encode/uvicorn/compare/0.21.0...0.21.1) --- updated-dependencies: - dependency-name: uvicorn dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 9e17424f5..4eb05db12 100644 --- a/requirements.txt +++ b/requirements.txt @@ -36,7 +36,7 @@ sdnotify==0.3.2 # API Server fastapi==0.94.0 pydantic==1.10.6 -uvicorn==0.21.0 +uvicorn==0.21.1 pyjwt==2.6.0 aiofiles==23.1.0 psutil==5.9.4 From 4543a1fe02a31904afca5016035f89571f5ba3da Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 20 Mar 2023 03:57:33 +0000 Subject: [PATCH 199/229] Bump pre-commit from 3.1.1 to 3.2.0 Bumps [pre-commit](https://github.com/pre-commit/pre-commit) from 3.1.1 to 3.2.0. - [Release notes](https://github.com/pre-commit/pre-commit/releases) - [Changelog](https://github.com/pre-commit/pre-commit/blob/main/CHANGELOG.md) - [Commits](https://github.com/pre-commit/pre-commit/compare/v3.1.1...v3.2.0) --- updated-dependencies: - dependency-name: pre-commit dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 6d076777f..c0dc815e2 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -9,7 +9,7 @@ coveralls==3.3.1 ruff==0.0.255 mypy==1.1.1 -pre-commit==3.1.1 +pre-commit==3.2.0 pytest==7.2.2 pytest-asyncio==0.20.3 pytest-cov==4.0.0 From 29b9be9bd0c14199aaf0c36a59207c06a6c3c79c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 20 Mar 2023 03:57:47 +0000 Subject: [PATCH 200/229] Bump ruff from 0.0.255 to 0.0.257 Bumps [ruff](https://github.com/charliermarsh/ruff) from 0.0.255 to 0.0.257. - [Release notes](https://github.com/charliermarsh/ruff/releases) - [Changelog](https://github.com/charliermarsh/ruff/blob/main/BREAKING_CHANGES.md) - [Commits](https://github.com/charliermarsh/ruff/compare/v0.0.255...v0.0.257) --- updated-dependencies: - dependency-name: ruff dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 6d076777f..8780a6d22 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -7,7 +7,7 @@ -r docs/requirements-docs.txt coveralls==3.3.1 -ruff==0.0.255 +ruff==0.0.257 mypy==1.1.1 pre-commit==3.1.1 pytest==7.2.2 From c78342b1943cf58bc2e78a94165d5281d9205cfa Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 20 Mar 2023 03:58:15 +0000 Subject: [PATCH 201/229] Bump pypa/gh-action-pypi-publish from 1.7.1 to 1.8.1 Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.7.1 to 1.8.1. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.7.1...v1.8.1) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 663cfb1be..904387fb2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -425,7 +425,7 @@ jobs: python setup.py sdist bdist_wheel - name: Publish to PyPI (Test) - uses: pypa/gh-action-pypi-publish@v1.7.1 + uses: pypa/gh-action-pypi-publish@v1.8.1 if: (github.event_name == 'release') with: user: __token__ @@ -433,7 +433,7 @@ jobs: repository_url: https://test.pypi.org/legacy/ - name: Publish to PyPI - uses: pypa/gh-action-pypi-publish@v1.7.1 + uses: pypa/gh-action-pypi-publish@v1.8.1 if: (github.event_name == 'release') with: user: __token__ From dcca51985d89d5b39e0497dd75249b2387639b2a Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 20 Mar 2023 06:27:39 +0100 Subject: [PATCH 202/229] sqlalchemy - pre-commit --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index bc2e0bc0d..ca3da8e90 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -18,7 +18,7 @@ repos: - types-requests==2.28.11.15 - types-tabulate==0.9.0.1 - types-python-dateutil==2.8.19.10 - - SQLAlchemy==2.0.5.post1 + - SQLAlchemy==2.0.7 # stages: [push] - repo: https://github.com/pycqa/isort From 2de5a59d890e2345eb1a935554b3453ab4047416 Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 20 Mar 2023 06:38:42 +0100 Subject: [PATCH 203/229] Add test for dry-run fetching --- tests/exchange/test_okx.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tests/exchange/test_okx.py b/tests/exchange/test_okx.py index 30e23619b..2f862adda 100644 --- a/tests/exchange/test_okx.py +++ b/tests/exchange/test_okx.py @@ -528,3 +528,19 @@ def test_fetch_stoploss_order_okx(default_conf, mocker): assert resp['id'] == '1234' assert resp['id_stop'] == '123455' assert resp['type'] == 'stoploss' + + default_conf['dry_run'] = True + exchange = get_patched_exchange(mocker, default_conf, api_mock, id='okx') + dro_mock = mocker.patch(f"{EXMS}.fetch_dry_run_order", MagicMock(return_value={'id': '123455'})) + + api_mock.fetch_order.reset_mock() + api_mock.fetch_open_orders.reset_mock() + api_mock.fetch_closed_orders.reset_mock() + api_mock.fetch_canceled_orders.reset_mock() + resp = exchange.fetch_stoploss_order('1234', 'ETH/BTC') + + assert api_mock.fetch_order.call_count == 0 + assert api_mock.fetch_open_orders.call_count == 0 + assert api_mock.fetch_closed_orders.call_count == 0 + assert api_mock.fetch_canceled_orders.call_count == 0 + assert dro_mock.call_count == 1 From 4690244673175e708ed097ca22edcc4e9e432281 Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 20 Mar 2023 06:40:57 +0100 Subject: [PATCH 204/229] Enable okx stop-price types --- tests/exchange/test_exchange.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/exchange/test_exchange.py b/tests/exchange/test_exchange.py index 7c48f1c9d..6e15abaf4 100644 --- a/tests/exchange/test_exchange.py +++ b/tests/exchange/test_exchange.py @@ -1039,9 +1039,9 @@ def test_validate_ordertypes(default_conf, mocker): ('bybit', 'last', True), ('bybit', 'mark', True), ('bybit', 'index', True), - # ('okx', 'last', True), - # ('okx', 'mark', True), - # ('okx', 'index', True), + ('okx', 'last', True), + ('okx', 'mark', True), + ('okx', 'index', True), ('gate', 'last', True), ('gate', 'mark', True), ('gate', 'index', True), From 54d8aa7782160d5cf0da4074bf90e134205885fb Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 20 Mar 2023 06:46:00 +0100 Subject: [PATCH 205/229] Test stoploss_adjust okx --- tests/exchange/test_okx.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/exchange/test_okx.py b/tests/exchange/test_okx.py index 2f862adda..3b97e03f4 100644 --- a/tests/exchange/test_okx.py +++ b/tests/exchange/test_okx.py @@ -544,3 +544,18 @@ def test_fetch_stoploss_order_okx(default_conf, mocker): assert api_mock.fetch_closed_orders.call_count == 0 assert api_mock.fetch_canceled_orders.call_count == 0 assert dro_mock.call_count == 1 + + +@pytest.mark.parametrize('sl1,sl2,sl3,side', [ + (1501, 1499, 1501, "sell"), + (1499, 1501, 1499, "buy") +]) +def test_stoploss_adjust_okx(mocker, default_conf, sl1, sl2, sl3, side): + exchange = get_patched_exchange(mocker, default_conf, id='okx') + order = { + 'type': 'stoploss', + 'price': 1500, + 'stopLossPrice': 1500, + } + assert exchange.stoploss_adjust(sl1, order, side=side) + assert not exchange.stoploss_adjust(sl2, order, side=side) From 8d649988ca4cdb1eb558545c8025bfedd6accb41 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 20 Mar 2023 05:47:47 +0000 Subject: [PATCH 206/229] Bump fastapi from 0.94.0 to 0.95.0 Bumps [fastapi](https://github.com/tiangolo/fastapi) from 0.94.0 to 0.95.0. - [Release notes](https://github.com/tiangolo/fastapi/releases) - [Commits](https://github.com/tiangolo/fastapi/compare/0.94.0...0.95.0) --- updated-dependencies: - dependency-name: fastapi dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 664d1752e..201c46106 100644 --- a/requirements.txt +++ b/requirements.txt @@ -34,7 +34,7 @@ orjson==3.8.7 sdnotify==0.3.2 # API Server -fastapi==0.94.0 +fastapi==0.95.0 pydantic==1.10.6 uvicorn==0.21.1 pyjwt==2.6.0 From 3175121030b477514eb603a7ec2ebea5e5673e34 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 20 Mar 2023 05:47:55 +0000 Subject: [PATCH 207/229] Bump ast-comments from 1.0.0 to 1.0.1 Bumps [ast-comments](https://github.com/t3rn0/ast-comments) from 1.0.0 to 1.0.1. - [Release notes](https://github.com/t3rn0/ast-comments/releases) - [Commits](https://github.com/t3rn0/ast-comments/compare/1.0.0...1.0.1) --- updated-dependencies: - dependency-name: ast-comments dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 664d1752e..4251c879a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -56,4 +56,4 @@ schedule==1.1.0 websockets==10.4 janus==1.0.0 -ast-comments==1.0.0 +ast-comments==1.0.1 From cb1f971d4bb1bd9559529b6c5734acfc55a773a6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 20 Mar 2023 06:39:13 +0000 Subject: [PATCH 208/229] Bump ccxt from 2.9.12 to 3.0.23 Bumps [ccxt](https://github.com/ccxt/ccxt) from 2.9.12 to 3.0.23. - [Release notes](https://github.com/ccxt/ccxt/releases) - [Changelog](https://github.com/ccxt/ccxt/blob/master/CHANGELOG.md) - [Commits](https://github.com/ccxt/ccxt/compare/2.9.12...3.0.23) --- updated-dependencies: - dependency-name: ccxt dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index de38d50c3..6f16c71d0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,7 +2,7 @@ numpy==1.24.2 pandas==1.5.3 pandas-ta==0.3.14b -ccxt==2.9.12 +ccxt==3.0.23 cryptography==39.0.2 aiohttp==3.8.4 SQLAlchemy==2.0.7 From a4e4310d400b73c15236ebaab36dfa7876dc9330 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 20 Mar 2023 07:11:18 +0000 Subject: [PATCH 209/229] Bump pytest-asyncio from 0.20.3 to 0.21.0 Bumps [pytest-asyncio](https://github.com/pytest-dev/pytest-asyncio) from 0.20.3 to 0.21.0. - [Release notes](https://github.com/pytest-dev/pytest-asyncio/releases) - [Commits](https://github.com/pytest-dev/pytest-asyncio/compare/v0.20.3...v0.21.0) --- updated-dependencies: - dependency-name: pytest-asyncio dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- requirements-dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 25e26f47c..8312e2820 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -11,7 +11,7 @@ ruff==0.0.257 mypy==1.1.1 pre-commit==3.2.0 pytest==7.2.2 -pytest-asyncio==0.20.3 +pytest-asyncio==0.21.0 pytest-cov==4.0.0 pytest-mock==3.10.0 pytest-random-order==1.1.0 From 4f4bfdac4d2491277decca93cdd30aec9ec29a1a Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 20 Mar 2023 09:00:00 +0100 Subject: [PATCH 210/229] Adjustments to okx stoploss --- freqtrade/exchange/okx.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/freqtrade/exchange/okx.py b/freqtrade/exchange/okx.py index 7de110acf..3110d8189 100644 --- a/freqtrade/exchange/okx.py +++ b/freqtrade/exchange/okx.py @@ -32,7 +32,7 @@ class Okx(Exchange): _ft_has_futures: Dict = { "tickers_have_quoteVolume": False, "fee_cost_in_contracts": True, - "stop_price_type_field": "tpTriggerPxType", + "stop_price_type_field": "slTriggerPxType", "stop_price_type_value_mapping": { PriceType.LAST: "last", PriceType.MARK: "index", @@ -193,7 +193,7 @@ class Okx(Exchange): try: params1 = {'stop': True} order_reg = self._api.fetch_order(order_id, pair, params=params1) - self._log_exchange_response('fetch_stoploss_order1', order_reg) + self._log_exchange_response('fetch_stoploss_order', order_reg) return order_reg except ccxt.OrderNotFound: pass From 639987cbabc8ae969f280639ffa856af99402064 Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 20 Mar 2023 18:19:17 +0100 Subject: [PATCH 211/229] Prevent parameter reuse --- freqtrade/exchange/okx.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/freqtrade/exchange/okx.py b/freqtrade/exchange/okx.py index 3110d8189..162630ea5 100644 --- a/freqtrade/exchange/okx.py +++ b/freqtrade/exchange/okx.py @@ -197,11 +197,11 @@ class Okx(Exchange): return order_reg except ccxt.OrderNotFound: pass - params1 = {'stop': True, 'ordType': 'conditional'} + params2 = {'stop': True, 'ordType': 'conditional'} for method in (self._api.fetch_open_orders, self._api.fetch_closed_orders, self._api.fetch_canceled_orders): try: - orders = method(pair, params=params1) + orders = method(pair, params=params2) orders_f = [order for order in orders if order['id'] == order_id] if orders_f: order = orders_f[0] From 97c420b2df8c2fe49c5c14b264836b1af58111f7 Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 20 Mar 2023 19:27:48 +0100 Subject: [PATCH 212/229] Add explicit test for okx lev_prep --- freqtrade/exchange/okx.py | 1 - tests/exchange/test_okx.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/freqtrade/exchange/okx.py b/freqtrade/exchange/okx.py index 162630ea5..1b9134be3 100644 --- a/freqtrade/exchange/okx.py +++ b/freqtrade/exchange/okx.py @@ -128,7 +128,6 @@ class Okx(Exchange): def _lev_prep(self, pair: str, leverage: float, side: BuySell): if self.trading_mode != TradingMode.SPOT and self.margin_mode is not None: try: - # TODO-lev: Test me properly (check mgnMode passed) res = self._api.set_leverage( leverage=leverage, symbol=pair, diff --git a/tests/exchange/test_okx.py b/tests/exchange/test_okx.py index 3b97e03f4..7a3fa22f0 100644 --- a/tests/exchange/test_okx.py +++ b/tests/exchange/test_okx.py @@ -480,6 +480,38 @@ def test_load_leverage_tiers_okx(default_conf, mocker, markets, tmpdir, caplog, assert log_has(logmsg, caplog) +def test__set_leverage_okx(mocker, default_conf): + + api_mock = MagicMock() + api_mock.set_leverage = MagicMock() + type(api_mock).has = PropertyMock(return_value={'setLeverage': True}) + default_conf['dry_run'] = False + default_conf['trading_mode'] = TradingMode.FUTURES + default_conf['margin_mode'] = MarginMode.ISOLATED + + exchange = get_patched_exchange(mocker, default_conf, api_mock, id="okx") + exchange._lev_prep('BTC/USDT:USDT', 3.2, 'buy') + assert api_mock.set_leverage.call_count == 1 + # Leverage is rounded to 3. + assert api_mock.set_leverage.call_args_list[0][1]['leverage'] == 3.2 + assert api_mock.set_leverage.call_args_list[0][1]['symbol'] == 'BTC/USDT:USDT' + assert api_mock.set_leverage.call_args_list[0][1]['params'] == { + 'mgnMode': 'isolated', + 'posSide': 'net'} + + ccxt_exceptionhandlers( + mocker, + default_conf, + api_mock, + "okx", + "_lev_prep", + "set_leverage", + pair="XRP/USDT:USDT", + leverage=5.0, + side='buy' + ) + + @pytest.mark.usefixtures("init_persistence") def test_fetch_stoploss_order_okx(default_conf, mocker): default_conf['dry_run'] = False From 36c45fd14f8daa25240b585757af38cfc3663564 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 21 Mar 2023 19:14:09 +0100 Subject: [PATCH 213/229] Remove unused argument from set_leverage --- freqtrade/exchange/exchange.py | 1 - freqtrade/exchange/kraken.py | 1 - tests/exchange/test_binance.py | 1 - tests/exchange/test_exchange.py | 23 ----------------------- 4 files changed, 26 deletions(-) diff --git a/freqtrade/exchange/exchange.py b/freqtrade/exchange/exchange.py index e5f897c2a..f620b5bc1 100644 --- a/freqtrade/exchange/exchange.py +++ b/freqtrade/exchange/exchange.py @@ -2527,7 +2527,6 @@ class Exchange: self, leverage: float, pair: Optional[str] = None, - trading_mode: Optional[TradingMode] = None, accept_fail: bool = False, ): """ diff --git a/freqtrade/exchange/kraken.py b/freqtrade/exchange/kraken.py index 8a4f7f7e0..b1a19fa69 100644 --- a/freqtrade/exchange/kraken.py +++ b/freqtrade/exchange/kraken.py @@ -158,7 +158,6 @@ class Kraken(Exchange): self, leverage: float, pair: Optional[str] = None, - trading_mode: Optional[TradingMode] = None, accept_fail: bool = False, ): """ diff --git a/tests/exchange/test_binance.py b/tests/exchange/test_binance.py index ba786bb3b..8ada089bd 100644 --- a/tests/exchange/test_binance.py +++ b/tests/exchange/test_binance.py @@ -555,7 +555,6 @@ def test__set_leverage_binance(mocker, default_conf): "set_leverage", pair="XRP/USDT", leverage=5.0, - trading_mode=TradingMode.FUTURES ) diff --git a/tests/exchange/test_exchange.py b/tests/exchange/test_exchange.py index 6e15abaf4..586f023b4 100644 --- a/tests/exchange/test_exchange.py +++ b/tests/exchange/test_exchange.py @@ -3868,29 +3868,6 @@ def test_get_stake_amount_considering_leverage( stake_amount, leverage) == min_stake_with_lev -@pytest.mark.parametrize("exchange_name,trading_mode", [ - ("binance", TradingMode.FUTURES), -]) -def test__set_leverage(mocker, default_conf, exchange_name, trading_mode): - - api_mock = MagicMock() - api_mock.set_leverage = MagicMock() - type(api_mock).has = PropertyMock(return_value={'setLeverage': True}) - default_conf['dry_run'] = False - - ccxt_exceptionhandlers( - mocker, - default_conf, - api_mock, - exchange_name, - "_set_leverage", - "set_leverage", - pair="XRP/USDT", - leverage=5.0, - trading_mode=trading_mode - ) - - @pytest.mark.parametrize("margin_mode", [ (MarginMode.CROSS), (MarginMode.ISOLATED) From ebebcb886c0a3f6ac98460fbf073052c96a9f25e Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 21 Mar 2023 19:28:26 +0100 Subject: [PATCH 214/229] Move build-system to the top of pyproject.toml --- pyproject.toml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index c3ca9e1b0..baf707c68 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,3 +1,7 @@ +[build-system] +requires = ["setuptools >= 46.4.0", "wheel"] +build-backend = "setuptools.build_meta" + [tool.black] line-length = 100 exclude = ''' @@ -48,10 +52,6 @@ ignore_errors = true module = "telegram.*" implicit_optional = true -[build-system] -requires = ["setuptools >= 46.4.0", "wheel"] -build-backend = "setuptools.build_meta" - [tool.pyright] include = ["freqtrade"] exclude = [ From 8cf3e9f91b50fd7d615822e87a51aa997548dd59 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 21 Mar 2023 19:29:27 +0100 Subject: [PATCH 215/229] Accept "insufficient funds" error on set_leverage from stop calls closes #8341 --- freqtrade/exchange/bybit.py | 2 +- freqtrade/exchange/exchange.py | 10 +++++----- freqtrade/exchange/okx.py | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/freqtrade/exchange/bybit.py b/freqtrade/exchange/bybit.py index 6f841b608..a4b070741 100644 --- a/freqtrade/exchange/bybit.py +++ b/freqtrade/exchange/bybit.py @@ -114,7 +114,7 @@ class Bybit(Exchange): data = [[x['timestamp'], x['fundingRate'], 0, 0, 0, 0] for x in data] return data - def _lev_prep(self, pair: str, leverage: float, side: BuySell): + def _lev_prep(self, pair: str, leverage: float, side: BuySell, accept_fail: bool = False): if self.trading_mode != TradingMode.SPOT: params = {'leverage': leverage} self.set_margin_mode(pair, self.margin_mode, accept_fail=True, params=params) diff --git a/freqtrade/exchange/exchange.py b/freqtrade/exchange/exchange.py index f620b5bc1..99551b054 100644 --- a/freqtrade/exchange/exchange.py +++ b/freqtrade/exchange/exchange.py @@ -1018,10 +1018,10 @@ class Exchange: # Order handling - def _lev_prep(self, pair: str, leverage: float, side: BuySell): + def _lev_prep(self, pair: str, leverage: float, side: BuySell, accept_fail: bool = False): if self.trading_mode != TradingMode.SPOT: - self.set_margin_mode(pair, self.margin_mode) - self._set_leverage(leverage, pair) + self.set_margin_mode(pair, self.margin_mode, accept_fail) + self._set_leverage(leverage, pair, accept_fail) def _get_params( self, @@ -1202,7 +1202,7 @@ class Exchange: amount = self.amount_to_precision(pair, self._amount_to_contracts(pair, amount)) - self._lev_prep(pair, leverage, side) + self._lev_prep(pair, leverage, side, accept_fail=True) order = self._api.create_order(symbol=pair, type=ordertype, side=side, amount=amount, price=limit_rate, params=params) self._log_exchange_response('create_stoploss_order', order) @@ -2544,7 +2544,7 @@ class Exchange: self._log_exchange_response('set_leverage', res) except ccxt.DDoSProtection as e: raise DDosProtection(e) from e - except ccxt.BadRequest as e: + except (ccxt.BadRequest, ccxt.InsufficientFunds) as e: if not accept_fail: raise TemporaryError( f'Could not set leverage due to {e.__class__.__name__}. Message: {e}') from e diff --git a/freqtrade/exchange/okx.py b/freqtrade/exchange/okx.py index 1b9134be3..a4fcaeca0 100644 --- a/freqtrade/exchange/okx.py +++ b/freqtrade/exchange/okx.py @@ -125,7 +125,7 @@ class Okx(Exchange): return params @retrier - def _lev_prep(self, pair: str, leverage: float, side: BuySell): + def _lev_prep(self, pair: str, leverage: float, side: BuySell, accept_fail: bool = False): if self.trading_mode != TradingMode.SPOT and self.margin_mode is not None: try: res = self._api.set_leverage( From bdf19f1d6622272c4f607080eea347854e13ac02 Mon Sep 17 00:00:00 2001 From: Robert Caulk Date: Tue, 21 Mar 2023 22:44:56 +0100 Subject: [PATCH 216/229] Update freqai_interface.py --- freqtrade/freqai/freqai_interface.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/freqtrade/freqai/freqai_interface.py b/freqtrade/freqai/freqai_interface.py index 07c357de3..8e842b8f2 100644 --- a/freqtrade/freqai/freqai_interface.py +++ b/freqtrade/freqai/freqai_interface.py @@ -105,6 +105,10 @@ class IFreqaiModel(ABC): self.max_system_threads = max(int(psutil.cpu_count() * 2 - 2), 1) self.can_short = True # overridden in start() with strategy.can_short self.model: Any = None + if self.ft_params.get('principal_component_analysis', False) and self.continual_learning: + self.ft_params.update({'principal_component_analysis': False}) + logger.warning('User tried to use PCA with continual learning. Deactivating PCA.') + record_params(config, self.full_path) @@ -154,8 +158,7 @@ class IFreqaiModel(ABC): dk = self.start_backtesting(dataframe, metadata, self.dk, strategy) dataframe = dk.remove_features_from_df(dk.return_dataframe) else: - logger.info( - "Backtesting using historic predictions (live models)") + logger.info("Backtesting using historic predictions (live models)") dk = self.start_backtesting_from_historic_predictions( dataframe, metadata, self.dk) dataframe = dk.return_dataframe From 150c5510c74390641fd723f6a70b5f67f53ec9cf Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 22 Mar 2023 19:46:07 +0100 Subject: [PATCH 217/229] Don''t fully fail bot when invalid price value is reached closes #8300 --- freqtrade/exchange/exchange.py | 6 +++++- freqtrade/freqtradebot.py | 14 +++++++++----- tests/exchange/test_binance.py | 4 ++-- tests/exchange/test_huobi.py | 6 +++--- tests/exchange/test_kucoin.py | 6 +++--- 5 files changed, 22 insertions(+), 14 deletions(-) diff --git a/freqtrade/exchange/exchange.py b/freqtrade/exchange/exchange.py index 99551b054..104eaa221 100644 --- a/freqtrade/exchange/exchange.py +++ b/freqtrade/exchange/exchange.py @@ -1135,7 +1135,11 @@ class Exchange: "sell" else (stop_price >= limit_rate)) # Ensure rate is less than stop price if bad_stop_price: - raise OperationalException( + # This can for example happen if the stop / liquidation price is set to 0 + # Which is possible if a market-order closes right away. + # The InvalidOrderException will bubble up to exit_positions, where it will be + # handled gracefully. + raise InvalidOrderException( "In stoploss limit order, stop price should be more than limit price. " f"Stop price: {stop_price}, Limit price: {limit_rate}, " f"Limit Price pct: {limit_price_pct}" diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index 06c8831f5..00bfc1ee2 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -1021,12 +1021,16 @@ class FreqtradeBot(LoggingMixin): trades_closed = 0 for trade in trades: try: + try: + if (self.strategy.order_types.get('stoploss_on_exchange') and + self.handle_stoploss_on_exchange(trade)): + trades_closed += 1 + Trade.commit() + continue - if (self.strategy.order_types.get('stoploss_on_exchange') and - self.handle_stoploss_on_exchange(trade)): - trades_closed += 1 - Trade.commit() - continue + except InvalidOrderException as exception: + logger.warning( + f'Unable to handle stoploss on exchange for {trade.pair}: {exception}') # Check if we can sell our current pair if trade.open_order_id is None and trade.is_open and self.handle_trade(trade): trades_closed += 1 diff --git a/tests/exchange/test_binance.py b/tests/exchange/test_binance.py index 8ada089bd..273860e15 100644 --- a/tests/exchange/test_binance.py +++ b/tests/exchange/test_binance.py @@ -52,7 +52,7 @@ def test_create_stoploss_order_binance(default_conf, mocker, limitratio, expecte exchange = get_patched_exchange(mocker, default_conf, api_mock, 'binance') - with pytest.raises(OperationalException): + with pytest.raises(InvalidOrderException): order = exchange.create_stoploss( pair='ETH/BTC', amount=1, @@ -131,7 +131,7 @@ def test_create_stoploss_order_dry_run_binance(default_conf, mocker): exchange = get_patched_exchange(mocker, default_conf, api_mock, 'binance') - with pytest.raises(OperationalException): + with pytest.raises(InvalidOrderException): order = exchange.create_stoploss( pair='ETH/BTC', amount=1, diff --git a/tests/exchange/test_huobi.py b/tests/exchange/test_huobi.py index 5e4fd7316..85d2ced9d 100644 --- a/tests/exchange/test_huobi.py +++ b/tests/exchange/test_huobi.py @@ -4,7 +4,7 @@ from unittest.mock import MagicMock import ccxt import pytest -from freqtrade.exceptions import DependencyException, InvalidOrderException, OperationalException +from freqtrade.exceptions import DependencyException, InvalidOrderException from tests.conftest import EXMS, get_patched_exchange from tests.exchange.test_exchange import ccxt_exceptionhandlers @@ -31,7 +31,7 @@ def test_create_stoploss_order_huobi(default_conf, mocker, limitratio, expected, exchange = get_patched_exchange(mocker, default_conf, api_mock, 'huobi') - with pytest.raises(OperationalException): + with pytest.raises(InvalidOrderException): order = exchange.create_stoploss(pair='ETH/BTC', amount=1, stop_price=190, order_types={'stoploss_on_exchange_limit_ratio': 1.05}, side=side, @@ -84,7 +84,7 @@ def test_create_stoploss_order_dry_run_huobi(default_conf, mocker): exchange = get_patched_exchange(mocker, default_conf, api_mock, 'huobi') - with pytest.raises(OperationalException): + with pytest.raises(InvalidOrderException): order = exchange.create_stoploss(pair='ETH/BTC', amount=1, stop_price=190, order_types={'stoploss_on_exchange_limit_ratio': 1.05}, side='sell', leverage=1.0) diff --git a/tests/exchange/test_kucoin.py b/tests/exchange/test_kucoin.py index e0bb32b7c..07f3fb6a3 100644 --- a/tests/exchange/test_kucoin.py +++ b/tests/exchange/test_kucoin.py @@ -4,7 +4,7 @@ from unittest.mock import MagicMock import ccxt import pytest -from freqtrade.exceptions import DependencyException, InvalidOrderException, OperationalException +from freqtrade.exceptions import DependencyException, InvalidOrderException from tests.conftest import EXMS, get_patched_exchange from tests.exchange.test_exchange import ccxt_exceptionhandlers @@ -31,7 +31,7 @@ def test_create_stoploss_order_kucoin(default_conf, mocker, limitratio, expected exchange = get_patched_exchange(mocker, default_conf, api_mock, 'kucoin') if order_type == 'limit': - with pytest.raises(OperationalException): + with pytest.raises(InvalidOrderException): order = exchange.create_stoploss(pair='ETH/BTC', amount=1, stop_price=190, order_types={ 'stoploss': order_type, @@ -92,7 +92,7 @@ def test_stoploss_order_dry_run_kucoin(default_conf, mocker): exchange = get_patched_exchange(mocker, default_conf, api_mock, 'kucoin') - with pytest.raises(OperationalException): + with pytest.raises(InvalidOrderException): order = exchange.create_stoploss(pair='ETH/BTC', amount=1, stop_price=190, order_types={'stoploss': 'limit', 'stoploss_on_exchange_limit_ratio': 1.05}, From 469166636c9794afb309875d87be66e76518430e Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 24 Mar 2023 07:27:45 +0100 Subject: [PATCH 218/229] Set initial stoploss when creating the order This ensures that a trade never has "None" as stoploss --- freqtrade/freqtradebot.py | 3 +++ tests/rpc/test_rpc.py | 11 ----------- tests/test_integration.py | 18 +++++++++--------- 3 files changed, 12 insertions(+), 20 deletions(-) diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index 00bfc1ee2..9d402b6a6 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -810,6 +810,9 @@ class FreqtradeBot(LoggingMixin): precision_mode=self.exchange.precisionMode, contract_size=self.exchange.get_contract_size(pair), ) + stoploss = self.strategy.stoploss if not self.edge else self.edge.get_stoploss(pair) + trade.adjust_stop_loss(trade.open_rate, stoploss, initial=True) + else: # This is additional buy, we reset fee_open_currency so timeout checking can work trade.is_open = True diff --git a/tests/rpc/test_rpc.py b/tests/rpc/test_rpc.py index 7d829bdb6..4e2dc94ae 100644 --- a/tests/rpc/test_rpc.py +++ b/tests/rpc/test_rpc.py @@ -125,17 +125,6 @@ def test_rpc_trade_status(default_conf, ticker, fee, mocker) -> None: 'profit_pct': 0.0, 'profit_abs': 0.0, 'total_profit_abs': 0.0, - 'stop_loss_abs': 0.0, - 'stop_loss_pct': None, - 'stop_loss_ratio': None, - 'stoploss_current_dist': -1.099e-05, - 'stoploss_current_dist_ratio': -1.0, - 'stoploss_current_dist_pct': pytest.approx(-100.0), - 'stoploss_entry_dist': -0.0010025, - 'stoploss_entry_dist_ratio': -1.0, - 'initial_stop_loss_abs': 0.0, - 'initial_stop_loss_pct': None, - 'initial_stop_loss_ratio': None, 'open_order': '(limit buy rem=91.07468123)', }) response_unfilled['orders'][0].update({ diff --git a/tests/test_integration.py b/tests/test_integration.py index 922285309..5cbedd818 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -386,12 +386,12 @@ def test_dca_order_adjust(default_conf_usdt, ticker_usdt, leverage, fee, mocker) assert trade.open_order_id is not None assert pytest.approx(trade.stake_amount) == 60 assert trade.open_rate == 1.96 - assert trade.stop_loss_pct is None - assert trade.stop_loss == 0.0 + assert trade.stop_loss_pct == -0.1 + assert pytest.approx(trade.stop_loss) == trade.open_rate * (1 - 0.1 / leverage) + assert pytest.approx(trade.initial_stop_loss) == trade.open_rate * (1 - 0.1 / leverage) + assert trade.initial_stop_loss_pct == -0.1 assert trade.leverage == leverage assert trade.stake_amount == 60 - assert trade.initial_stop_loss == 0.0 - assert trade.initial_stop_loss_pct is None # No adjustment freqtrade.process() trade = Trade.get_trades().first() @@ -407,11 +407,11 @@ def test_dca_order_adjust(default_conf_usdt, ticker_usdt, leverage, fee, mocker) assert trade.open_order_id is not None # Open rate is not adjusted yet assert trade.open_rate == 1.96 - assert trade.stop_loss_pct is None - assert trade.stop_loss == 0.0 + assert trade.stop_loss_pct == -0.1 + assert pytest.approx(trade.stop_loss) == trade.open_rate * (1 - 0.1 / leverage) + assert pytest.approx(trade.initial_stop_loss) == trade.open_rate * (1 - 0.1 / leverage) assert trade.stake_amount == 60 - assert trade.initial_stop_loss == 0.0 - assert trade.initial_stop_loss_pct is None + assert trade.initial_stop_loss_pct == -0.1 # Fill order mocker.patch(f'{EXMS}._dry_is_price_crossed', return_value=True) @@ -424,7 +424,7 @@ def test_dca_order_adjust(default_conf_usdt, ticker_usdt, leverage, fee, mocker) assert pytest.approx(trade.stake_amount) == 60 assert trade.stop_loss_pct == -0.1 assert pytest.approx(trade.stop_loss) == 1.99 * (1 - 0.1 / leverage) - assert pytest.approx(trade.initial_stop_loss) == 1.99 * (1 - 0.1 / leverage) + assert pytest.approx(trade.initial_stop_loss) == 1.96 * (1 - 0.1 / leverage) assert trade.initial_stop_loss_pct == -0.1 # 2nd order - not filling From b317524ed70883a5d440827aeb52434b57a1602e Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 24 Mar 2023 20:27:45 +0100 Subject: [PATCH 219/229] protect adjust_trade_position from crashing in case of unsafe code --- freqtrade/freqtradebot.py | 2 +- freqtrade/optimize/backtesting.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index 9d402b6a6..623d39c09 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -594,7 +594,7 @@ class FreqtradeBot(LoggingMixin): stake_available = self.wallets.get_available_stake_amount() logger.debug(f"Calling adjust_trade_position for pair {trade.pair}") stake_amount = strategy_safe_wrapper(self.strategy.adjust_trade_position, - default_retval=None)( + default_retval=None, supress_error=True)( trade=trade, current_time=datetime.now(timezone.utc), current_rate=current_entry_rate, current_profit=current_entry_profit, min_stake=min_entry_stake, diff --git a/freqtrade/optimize/backtesting.py b/freqtrade/optimize/backtesting.py index 315b3b9db..fe6667ad9 100644 --- a/freqtrade/optimize/backtesting.py +++ b/freqtrade/optimize/backtesting.py @@ -522,7 +522,7 @@ class Backtesting: max_stake = self.exchange.get_max_pair_stake_amount(trade.pair, current_rate) stake_available = self.wallets.get_available_stake_amount() stake_amount = strategy_safe_wrapper(self.strategy.adjust_trade_position, - default_retval=None)( + default_retval=None, supress_error=True)( trade=trade, # type: ignore[arg-type] current_time=current_date, current_rate=current_rate, current_profit=current_profit, min_stake=min_stake, From 79a2de7a64a7a737bf6bdc593a187dd422453bb2 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 25 Mar 2023 08:31:35 +0100 Subject: [PATCH 220/229] Reduce impact of short outages --- tests/exchange/test_ccxt_compat.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/tests/exchange/test_ccxt_compat.py b/tests/exchange/test_ccxt_compat.py index 872cf5059..4a65b16d7 100644 --- a/tests/exchange/test_ccxt_compat.py +++ b/tests/exchange/test_ccxt_compat.py @@ -37,7 +37,7 @@ EXCHANGES = { 'stake_currency': 'USDT', 'use_ci_proxy': True, 'hasQuoteVolume': True, - 'timeframe': '5m', + 'timeframe': '1h', 'futures': True, 'futures_pair': 'BTC/USDT:USDT', 'hasQuoteVolumeFutures': True, @@ -66,7 +66,7 @@ EXCHANGES = { 'pair': 'BTC/USDT', 'stake_currency': 'USDT', 'hasQuoteVolume': True, - 'timeframe': '5m', + 'timeframe': '1h', 'futures': False, 'sample_order': [{ "symbol": "SOLUSDT", @@ -91,7 +91,7 @@ EXCHANGES = { 'pair': 'BTC/USDT', 'stake_currency': 'USDT', 'hasQuoteVolume': True, - 'timeframe': '5m', + 'timeframe': '1h', 'leverage_tiers_public': False, 'leverage_in_spot_market': True, }, @@ -99,7 +99,7 @@ EXCHANGES = { 'pair': 'XRP/USDT', 'stake_currency': 'USDT', 'hasQuoteVolume': True, - 'timeframe': '5m', + 'timeframe': '1h', 'leverage_tiers_public': False, 'leverage_in_spot_market': True, 'sample_order': [ @@ -141,7 +141,7 @@ EXCHANGES = { 'pair': 'BTC/USDT', 'stake_currency': 'USDT', 'hasQuoteVolume': True, - 'timeframe': '5m', + 'timeframe': '1h', 'futures': True, 'futures_pair': 'BTC/USDT:USDT', 'hasQuoteVolumeFutures': True, @@ -215,7 +215,7 @@ EXCHANGES = { 'pair': 'BTC/USDT', 'stake_currency': 'USDT', 'hasQuoteVolume': True, - 'timeframe': '5m', + 'timeframe': '1h', 'futures': True, 'futures_pair': 'BTC/USDT:USDT', 'hasQuoteVolumeFutures': False, @@ -226,7 +226,7 @@ EXCHANGES = { 'pair': 'BTC/USDT', 'stake_currency': 'USDT', 'hasQuoteVolume': True, - 'timeframe': '5m', + 'timeframe': '1h', 'futures_pair': 'BTC/USDT:USDT', 'futures': True, 'leverage_tiers_public': True, @@ -253,14 +253,14 @@ EXCHANGES = { 'pair': 'ETH/BTC', 'stake_currency': 'BTC', 'hasQuoteVolume': True, - 'timeframe': '5m', + 'timeframe': '1h', 'futures': False, }, 'bitvavo': { 'pair': 'BTC/EUR', 'stake_currency': 'EUR', 'hasQuoteVolume': True, - 'timeframe': '5m', + 'timeframe': '1h', 'leverage_tiers_public': False, 'leverage_in_spot_market': False, }, From 56170dba19b5d46fc5884e17d786b0f17fb0feda Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 25 Mar 2023 08:44:35 +0100 Subject: [PATCH 221/229] use github to download guess instead of gnu.org gnu.org seems down rn (dns does no longer resolve), and doesn't have good uptime history --- build_helpers/install_ta-lib.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build_helpers/install_ta-lib.sh b/build_helpers/install_ta-lib.sh index 079d578b4..005d9abca 100755 --- a/build_helpers/install_ta-lib.sh +++ b/build_helpers/install_ta-lib.sh @@ -8,8 +8,8 @@ if [ -n "$2" ] || [ ! -f "${INSTALL_LOC}/lib/libta_lib.a" ]; then tar zxvf ta-lib-0.4.0-src.tar.gz cd ta-lib \ && sed -i.bak "s|0.00000001|0.000000000000000001 |g" src/ta_func/ta_utility.h \ - && curl 'http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD' -o config.guess \ - && curl 'http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD' -o config.sub \ + && curl 'https://raw.githubusercontent.com/gcc-mirror/gcc/master/config.guess' -o config.guess \ + && curl 'https://raw.githubusercontent.com/gcc-mirror/gcc/master/config.sub' -o config.sub \ && ./configure --prefix=${INSTALL_LOC}/ \ && make if [ $? -ne 0 ]; then From cdd44a40058bd8bce80519d8f79007ff1034fb3a Mon Sep 17 00:00:00 2001 From: linquanisaac Date: Sat, 25 Mar 2023 17:19:58 +0800 Subject: [PATCH 222/229] docs(protections): fix typo --- docs/includes/protections.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/includes/protections.md b/docs/includes/protections.md index e0ad8189f..12af081c0 100644 --- a/docs/includes/protections.md +++ b/docs/includes/protections.md @@ -149,7 +149,7 @@ The below example assumes a timeframe of 1 hour: * Locks each pair after selling for an additional 5 candles (`CooldownPeriod`), giving other pairs a chance to get filled. * Stops trading for 4 hours (`4 * 1h candles`) if the last 2 days (`48 * 1h candles`) had 20 trades, which caused a max-drawdown of more than 20%. (`MaxDrawdown`). * Stops trading if more than 4 stoploss occur for all pairs within a 1 day (`24 * 1h candles`) limit (`StoplossGuard`). -* Locks all pairs that had 4 Trades within the last 6 hours (`6 * 1h candles`) with a combined profit ratio of below 0.02 (<2%) (`LowProfitPairs`). +* Locks all pairs that had 2 Trades within the last 6 hours (`6 * 1h candles`) with a combined profit ratio of below 0.02 (<2%) (`LowProfitPairs`). * Locks all pairs for 2 candles that had a profit of below 0.01 (<1%) within the last 24h (`24 * 1h candles`), a minimum of 4 trades. ``` python From 9c6a49436bd17752a8c0921c801c642116658c95 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 25 Mar 2023 11:42:19 +0100 Subject: [PATCH 223/229] Export amount/price precisions per trade --- freqtrade/persistence/trade_model.py | 3 + tests/persistence/test_persistence.py | 256 ++++++++++++++------------ tests/rpc/test_rpc.py | 3 + 3 files changed, 141 insertions(+), 121 deletions(-) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 27be0d726..54ff1313b 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -560,6 +560,9 @@ class LocalTrade(): 'trading_mode': self.trading_mode, 'funding_fees': self.funding_fees, 'open_order_id': self.open_order_id, + 'amount_precision': self.amount_precision, + 'price_precision': self.price_precision, + 'precision_mode': self.precision_mode, 'orders': orders, } diff --git a/tests/persistence/test_persistence.py b/tests/persistence/test_persistence.py index db882d56d..23ec6d4fb 100644 --- a/tests/persistence/test_persistence.py +++ b/tests/persistence/test_persistence.py @@ -1330,71 +1330,78 @@ def test_to_json(fee): open_rate=0.123, exchange='binance', enter_tag=None, - open_order_id='dry_run_buy_12345' + open_order_id='dry_run_buy_12345', + precision_mode=1, + amount_precision=8.0, + price_precision=7.0, ) result = trade.to_json() assert isinstance(result, dict) - assert result == {'trade_id': None, - 'pair': 'ADA/USDT', - 'base_currency': 'ADA', - 'quote_currency': 'USDT', - 'is_open': None, - 'open_date': trade.open_date.strftime(DATETIME_PRINT_FORMAT), - 'open_timestamp': int(trade.open_date.timestamp() * 1000), - 'open_order_id': 'dry_run_buy_12345', - 'close_date': None, - 'close_timestamp': None, - 'open_rate': 0.123, - 'open_rate_requested': None, - 'open_trade_value': 15.1668225, - 'fee_close': 0.0025, - 'fee_close_cost': None, - 'fee_close_currency': None, - 'fee_open': 0.0025, - 'fee_open_cost': None, - 'fee_open_currency': None, - 'close_rate': None, - 'close_rate_requested': None, - 'amount': 123.0, - 'amount_requested': 123.0, - 'stake_amount': 0.001, - 'max_stake_amount': None, - 'trade_duration': None, - 'trade_duration_s': None, - 'realized_profit': 0.0, - 'realized_profit_ratio': None, - 'close_profit': None, - 'close_profit_pct': None, - 'close_profit_abs': None, - 'profit_ratio': None, - 'profit_pct': None, - 'profit_abs': None, - 'exit_reason': None, - 'exit_order_status': None, - 'stop_loss_abs': None, - 'stop_loss_ratio': None, - 'stop_loss_pct': None, - 'stoploss_order_id': None, - 'stoploss_last_update': None, - 'stoploss_last_update_timestamp': None, - 'initial_stop_loss_abs': None, - 'initial_stop_loss_pct': None, - 'initial_stop_loss_ratio': None, - 'min_rate': None, - 'max_rate': None, - 'strategy': None, - 'enter_tag': None, - 'timeframe': None, - 'exchange': 'binance', - 'leverage': None, - 'interest_rate': None, - 'liquidation_price': None, - 'is_short': None, - 'trading_mode': None, - 'funding_fees': None, - 'orders': [], - } + assert result == { + 'trade_id': None, + 'pair': 'ADA/USDT', + 'base_currency': 'ADA', + 'quote_currency': 'USDT', + 'is_open': None, + 'open_date': trade.open_date.strftime(DATETIME_PRINT_FORMAT), + 'open_timestamp': int(trade.open_date.timestamp() * 1000), + 'open_order_id': 'dry_run_buy_12345', + 'close_date': None, + 'close_timestamp': None, + 'open_rate': 0.123, + 'open_rate_requested': None, + 'open_trade_value': 15.1668225, + 'fee_close': 0.0025, + 'fee_close_cost': None, + 'fee_close_currency': None, + 'fee_open': 0.0025, + 'fee_open_cost': None, + 'fee_open_currency': None, + 'close_rate': None, + 'close_rate_requested': None, + 'amount': 123.0, + 'amount_requested': 123.0, + 'stake_amount': 0.001, + 'max_stake_amount': None, + 'trade_duration': None, + 'trade_duration_s': None, + 'realized_profit': 0.0, + 'realized_profit_ratio': None, + 'close_profit': None, + 'close_profit_pct': None, + 'close_profit_abs': None, + 'profit_ratio': None, + 'profit_pct': None, + 'profit_abs': None, + 'exit_reason': None, + 'exit_order_status': None, + 'stop_loss_abs': None, + 'stop_loss_ratio': None, + 'stop_loss_pct': None, + 'stoploss_order_id': None, + 'stoploss_last_update': None, + 'stoploss_last_update_timestamp': None, + 'initial_stop_loss_abs': None, + 'initial_stop_loss_pct': None, + 'initial_stop_loss_ratio': None, + 'min_rate': None, + 'max_rate': None, + 'strategy': None, + 'enter_tag': None, + 'timeframe': None, + 'exchange': 'binance', + 'leverage': None, + 'interest_rate': None, + 'liquidation_price': None, + 'is_short': None, + 'trading_mode': None, + 'funding_fees': None, + 'amount_precision': 8.0, + 'price_precision': 7.0, + 'precision_mode': 1, + 'orders': [], + } # Simulate dry_run entries trade = Trade( @@ -1410,70 +1417,77 @@ def test_to_json(fee): close_rate=0.125, enter_tag='buys_signal_001', exchange='binance', + precision_mode=2, + amount_precision=7.0, + price_precision=8.0, ) result = trade.to_json() assert isinstance(result, dict) - assert result == {'trade_id': None, - 'pair': 'XRP/BTC', - 'base_currency': 'XRP', - 'quote_currency': 'BTC', - 'open_date': trade.open_date.strftime(DATETIME_PRINT_FORMAT), - 'open_timestamp': int(trade.open_date.timestamp() * 1000), - 'close_date': trade.close_date.strftime(DATETIME_PRINT_FORMAT), - 'close_timestamp': int(trade.close_date.timestamp() * 1000), - 'open_rate': 0.123, - 'close_rate': 0.125, - 'amount': 100.0, - 'amount_requested': 101.0, - 'stake_amount': 0.001, - 'max_stake_amount': None, - 'trade_duration': 60, - 'trade_duration_s': 3600, - 'stop_loss_abs': None, - 'stop_loss_pct': None, - 'stop_loss_ratio': None, - 'stoploss_order_id': None, - 'stoploss_last_update': None, - 'stoploss_last_update_timestamp': None, - 'initial_stop_loss_abs': None, - 'initial_stop_loss_pct': None, - 'initial_stop_loss_ratio': None, - 'realized_profit': 0.0, - 'realized_profit_ratio': None, - 'close_profit': None, - 'close_profit_pct': None, - 'close_profit_abs': None, - 'profit_ratio': None, - 'profit_pct': None, - 'profit_abs': None, - 'close_rate_requested': None, - 'fee_close': 0.0025, - 'fee_close_cost': None, - 'fee_close_currency': None, - 'fee_open': 0.0025, - 'fee_open_cost': None, - 'fee_open_currency': None, - 'is_open': None, - 'max_rate': None, - 'min_rate': None, - 'open_order_id': None, - 'open_rate_requested': None, - 'open_trade_value': 12.33075, - 'exit_reason': None, - 'exit_order_status': None, - 'strategy': None, - 'enter_tag': 'buys_signal_001', - 'timeframe': None, - 'exchange': 'binance', - 'leverage': None, - 'interest_rate': None, - 'liquidation_price': None, - 'is_short': None, - 'trading_mode': None, - 'funding_fees': None, - 'orders': [], - } + assert result == { + 'trade_id': None, + 'pair': 'XRP/BTC', + 'base_currency': 'XRP', + 'quote_currency': 'BTC', + 'open_date': trade.open_date.strftime(DATETIME_PRINT_FORMAT), + 'open_timestamp': int(trade.open_date.timestamp() * 1000), + 'close_date': trade.close_date.strftime(DATETIME_PRINT_FORMAT), + 'close_timestamp': int(trade.close_date.timestamp() * 1000), + 'open_rate': 0.123, + 'close_rate': 0.125, + 'amount': 100.0, + 'amount_requested': 101.0, + 'stake_amount': 0.001, + 'max_stake_amount': None, + 'trade_duration': 60, + 'trade_duration_s': 3600, + 'stop_loss_abs': None, + 'stop_loss_pct': None, + 'stop_loss_ratio': None, + 'stoploss_order_id': None, + 'stoploss_last_update': None, + 'stoploss_last_update_timestamp': None, + 'initial_stop_loss_abs': None, + 'initial_stop_loss_pct': None, + 'initial_stop_loss_ratio': None, + 'realized_profit': 0.0, + 'realized_profit_ratio': None, + 'close_profit': None, + 'close_profit_pct': None, + 'close_profit_abs': None, + 'profit_ratio': None, + 'profit_pct': None, + 'profit_abs': None, + 'close_rate_requested': None, + 'fee_close': 0.0025, + 'fee_close_cost': None, + 'fee_close_currency': None, + 'fee_open': 0.0025, + 'fee_open_cost': None, + 'fee_open_currency': None, + 'is_open': None, + 'max_rate': None, + 'min_rate': None, + 'open_order_id': None, + 'open_rate_requested': None, + 'open_trade_value': 12.33075, + 'exit_reason': None, + 'exit_order_status': None, + 'strategy': None, + 'enter_tag': 'buys_signal_001', + 'timeframe': None, + 'exchange': 'binance', + 'leverage': None, + 'interest_rate': None, + 'liquidation_price': None, + 'is_short': None, + 'trading_mode': None, + 'funding_fees': None, + 'amount_precision': 7.0, + 'price_precision': 8.0, + 'precision_mode': 2, + 'orders': [], + } def test_stoploss_reinitialization(default_conf, fee): diff --git a/tests/rpc/test_rpc.py b/tests/rpc/test_rpc.py index 4e2dc94ae..ff08a0564 100644 --- a/tests/rpc/test_rpc.py +++ b/tests/rpc/test_rpc.py @@ -88,6 +88,9 @@ def test_rpc_trade_status(default_conf, ticker, fee, mocker) -> None: 'is_short': False, 'funding_fees': 0.0, 'trading_mode': TradingMode.SPOT, + 'amount_precision': 8.0, + 'price_precision': 8.0, + 'precision_mode': 2, 'orders': [{ 'amount': 91.07468123, 'average': 1.098e-05, 'safe_price': 1.098e-05, 'cost': 0.0009999999999054, 'filled': 91.07468123, 'ft_order_side': 'buy', From f7c1ee6d3e1aa9f40ba5329d70cbe3e291c77581 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 25 Mar 2023 11:55:47 +0100 Subject: [PATCH 224/229] add precision values to api schema --- freqtrade/rpc/api_server/api_schemas.py | 4 ++++ tests/rpc/test_rpc_apiserver.py | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/freqtrade/rpc/api_server/api_schemas.py b/freqtrade/rpc/api_server/api_schemas.py index 18621ccbd..7497b27f1 100644 --- a/freqtrade/rpc/api_server/api_schemas.py +++ b/freqtrade/rpc/api_server/api_schemas.py @@ -276,6 +276,10 @@ class TradeSchema(BaseModel): funding_fees: Optional[float] trading_mode: Optional[TradingMode] + amount_precision: Optional[float] + price_precision: Optional[float] + precision_mode: Optional[int] + class OpenTradeSchema(TradeSchema): stoploss_current_dist: Optional[float] diff --git a/tests/rpc/test_rpc_apiserver.py b/tests/rpc/test_rpc_apiserver.py index 97319b78b..bf9d6cc3b 100644 --- a/tests/rpc/test_rpc_apiserver.py +++ b/tests/rpc/test_rpc_apiserver.py @@ -1066,6 +1066,9 @@ def test_api_status(botclient, mocker, ticker, fee, markets, is_short, 'liquidation_price': None, 'funding_fees': None, 'trading_mode': ANY, + 'amount_precision': None, + 'price_precision': None, + 'precision_mode': None, 'orders': [ANY], } @@ -1271,6 +1274,9 @@ def test_api_force_entry(botclient, mocker, fee, endpoint): 'liquidation_price': None, 'funding_fees': None, 'trading_mode': 'spot', + 'amount_precision': None, + 'price_precision': None, + 'precision_mode': None, 'orders': [], } From 68154a1f52c002944132242a089de29f27b0196e Mon Sep 17 00:00:00 2001 From: robcaulk Date: Sat, 25 Mar 2023 11:57:52 +0100 Subject: [PATCH 225/229] document why users cant arbitrarily change parameter spaces... --- docs/freqai-running.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/freqai-running.md b/docs/freqai-running.md index 1eaee1bf2..f3ccc546f 100644 --- a/docs/freqai-running.md +++ b/docs/freqai-running.md @@ -128,6 +128,9 @@ The FreqAI specific parameter `label_period_candles` defines the offset (number You can choose to adopt a continual learning scheme by setting `"continual_learning": true` in the config. By enabling `continual_learning`, after training an initial model from scratch, subsequent trainings will start from the final model state of the preceding training. This gives the new model a "memory" of the previous state. By default, this is set to `False` which means that all new models are trained from scratch, without input from previous models. +???+ danger "Continual learning enforces a constant parameter space" + Since `continual_learning` means that the model parameter space *cannot* change between trainings, `principal_component_analysis` is automatically disabled when `continual_learning` is enabled. Hint: PCA changes the parameter space and the number of features, learn more about PCA [here](freqai-feature-engineering.md#data-dimensionality-reduction-with-principal-component-analysis). + ## Hyperopt You can hyperopt using the same command as for [typical Freqtrade hyperopt](hyperopt.md): From d9c8b322ce45c88abeb23ffc63ad815e10c72e74 Mon Sep 17 00:00:00 2001 From: Robert Caulk Date: Sat, 25 Mar 2023 13:37:07 +0100 Subject: [PATCH 226/229] Update freqai_interface.py --- freqtrade/freqai/freqai_interface.py | 1 - 1 file changed, 1 deletion(-) diff --git a/freqtrade/freqai/freqai_interface.py b/freqtrade/freqai/freqai_interface.py index 8e842b8f2..b657bd811 100644 --- a/freqtrade/freqai/freqai_interface.py +++ b/freqtrade/freqai/freqai_interface.py @@ -109,7 +109,6 @@ class IFreqaiModel(ABC): self.ft_params.update({'principal_component_analysis': False}) logger.warning('User tried to use PCA with continual learning. Deactivating PCA.') - record_params(config, self.full_path) def __getstate__(self): From 486d8a48a05befc9dee60da922f319b51aebc651 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 25 Mar 2023 19:36:28 +0100 Subject: [PATCH 227/229] Fix docs (buffer_train_data_candles is an integer, not a boolean) closes #8384 --- docs/freqai-parameter-table.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/freqai-parameter-table.md b/docs/freqai-parameter-table.md index f67ea8541..9822a895a 100644 --- a/docs/freqai-parameter-table.md +++ b/docs/freqai-parameter-table.md @@ -46,7 +46,7 @@ Mandatory parameters are marked as **Required** and have to be set in one of the | `outlier_protection_percentage` | Enable to prevent outlier detection methods from discarding too much data. If more than `outlier_protection_percentage` % of points are detected as outliers by the SVM or DBSCAN, FreqAI will log a warning message and ignore outlier detection, i.e., the original dataset will be kept intact. If the outlier protection is triggered, no predictions will be made based on the training dataset.
**Datatype:** Float.
Default: `30`. | `reverse_train_test_order` | Split the feature dataset (see below) and use the latest data split for training and test on historical split of the data. This allows the model to be trained up to the most recent data point, while avoiding overfitting. However, you should be careful to understand the unorthodox nature of this parameter before employing it.
**Datatype:** Boolean.
Default: `False` (no reversal). | `shuffle_after_split` | Split the data into train and test sets, and then shuffle both sets individually.
**Datatype:** Boolean.
Default: `False`. -| `buffer_train_data_candles` | Cut `buffer_train_data_candles` off the beginning and end of the training data *after* the indicators were populated. The main example use is when predicting maxima and minima, the argrelextrema function cannot know the maxima/minima at the edges of the timerange. To improve model accuracy, it is best to compute argrelextrema on the full timerange and then use this function to cut off the edges (buffer) by the kernel. In another case, if the targets are set to a shifted price movement, this buffer is unnecessary because the shifted candles at the end of the timerange will be NaN and FreqAI will automatically cut those off of the training dataset.
**Datatype:** Boolean.
Default: `False`. +| `buffer_train_data_candles` | Cut `buffer_train_data_candles` off the beginning and end of the training data *after* the indicators were populated. The main example use is when predicting maxima and minima, the argrelextrema function cannot know the maxima/minima at the edges of the timerange. To improve model accuracy, it is best to compute argrelextrema on the full timerange and then use this function to cut off the edges (buffer) by the kernel. In another case, if the targets are set to a shifted price movement, this buffer is unnecessary because the shifted candles at the end of the timerange will be NaN and FreqAI will automatically cut those off of the training dataset.
**Datatype:** Integer.
Default: `0`. ### Data split parameters From 298f5685ee3f3c902243efe0e953fb83076bffa6 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 25 Mar 2023 20:06:21 +0100 Subject: [PATCH 228/229] Reuse existing "cancel_stoploss" call --- freqtrade/freqtradebot.py | 12 ++++-------- tests/test_freqtradebot.py | 16 +++++++++------- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index 623d39c09..4482f37bf 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -854,7 +854,8 @@ class FreqtradeBot(LoggingMixin): # Reset stoploss order id. trade.stoploss_order_id = None except InvalidOrderException: - logger.exception(f"Could not cancel stoploss order {trade.stoploss_order_id}") + logger.exception(f"Could not cancel stoploss order {trade.stoploss_order_id} " + f"for pair {trade.pair}") return trade def get_valid_enter_price_and_stake( @@ -1239,13 +1240,8 @@ class FreqtradeBot(LoggingMixin): # cancelling the current stoploss on exchange first logger.info(f"Cancelling current stoploss on exchange for pair {trade.pair} " f"(orderid:{order['id']}) in order to add another one ...") - try: - co = self.exchange.cancel_stoploss_order_with_result(order['id'], trade.pair, - trade.amount) - trade.update_order(co) - except InvalidOrderException: - logger.exception(f"Could not cancel stoploss order {order['id']} " - f"for pair {trade.pair}") + + self.cancel_stoploss_on_exchange(trade) # Create new stoploss order if not self.create_stoploss_order(trade=trade, stop_price=stoploss_norm): diff --git a/tests/test_freqtradebot.py b/tests/test_freqtradebot.py index cea70ec48..ff10cd2f0 100644 --- a/tests/test_freqtradebot.py +++ b/tests/test_freqtradebot.py @@ -1440,11 +1440,11 @@ def test_handle_stoploss_on_exchange_trailing( trade.is_short = is_short trade.is_open = True trade.open_order_id = None - trade.stoploss_order_id = 100 + trade.stoploss_order_id = '100' trade.stoploss_last_update = arrow.utcnow().shift(minutes=-20).datetime stoploss_order_hanging = MagicMock(return_value={ - 'id': 100, + 'id': '100', 'status': 'open', 'type': 'stop_loss_limit', 'price': hang_price, @@ -1483,13 +1483,14 @@ def test_handle_stoploss_on_exchange_trailing( assert freqtrade.handle_trade(trade) is False assert trade.stop_loss == stop_price[1] + trade.stoploss_order_id = '100' # setting stoploss_on_exchange_interval to 0 seconds freqtrade.strategy.order_types['stoploss_on_exchange_interval'] = 0 assert freqtrade.handle_stoploss_on_exchange(trade) is False - cancel_order_mock.assert_called_once_with(100, 'ETH/USDT') + cancel_order_mock.assert_called_once_with('100', 'ETH/USDT') stoploss_order_mock.assert_called_once_with( amount=pytest.approx(amt), pair='ETH/USDT', @@ -1673,11 +1674,11 @@ def test_handle_stoploss_on_exchange_custom_stop( trade.is_short = is_short trade.is_open = True trade.open_order_id = None - trade.stoploss_order_id = 100 + trade.stoploss_order_id = '100' trade.stoploss_last_update = arrow.utcnow().shift(minutes=-601).datetime stoploss_order_hanging = MagicMock(return_value={ - 'id': 100, + 'id': '100', 'status': 'open', 'type': 'stop_loss_limit', 'price': 3, @@ -1706,6 +1707,7 @@ def test_handle_stoploss_on_exchange_custom_stop( stoploss_order_mock = MagicMock(return_value={'id': 'so1'}) mocker.patch(f'{EXMS}.cancel_stoploss_order', cancel_order_mock) mocker.patch(f'{EXMS}.create_stoploss', stoploss_order_mock) + trade.stoploss_order_id = '100' # stoploss should not be updated as the interval is 60 seconds assert freqtrade.handle_trade(trade) is False @@ -1722,7 +1724,7 @@ def test_handle_stoploss_on_exchange_custom_stop( assert freqtrade.handle_stoploss_on_exchange(trade) is False - cancel_order_mock.assert_called_once_with(100, 'ETH/USDT') + cancel_order_mock.assert_called_once_with('100', 'ETH/USDT') # Long uses modified ask - offset, short modified bid + offset stoploss_order_mock.assert_called_once_with( amount=pytest.approx(trade.amount), @@ -3588,7 +3590,7 @@ def test_execute_trade_exit_sloe_cancel_exception( freqtrade.execute_trade_exit(trade=trade, limit=1234, exit_check=ExitCheckTuple(exit_type=ExitType.STOP_LOSS)) assert create_order_mock.call_count == 2 - assert log_has('Could not cancel stoploss order abcd', caplog) + assert log_has('Could not cancel stoploss order abcd for pair ETH/USDT', caplog) @pytest.mark.parametrize("is_short", [False, True]) From ee205ddc862ee0105e570deed47b728272d21521 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 25 Mar 2023 20:26:56 +0100 Subject: [PATCH 229/229] Improve trade.from_json when stops are used --- freqtrade/persistence/trade_model.py | 6 ++++-- tests/persistence/test_trade_fromjson.py | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/freqtrade/persistence/trade_model.py b/freqtrade/persistence/trade_model.py index 54ff1313b..17117d436 100644 --- a/freqtrade/persistence/trade_model.py +++ b/freqtrade/persistence/trade_model.py @@ -1663,8 +1663,10 @@ class Trade(ModelBase, LocalTrade): stop_loss=data["stop_loss_abs"], stop_loss_pct=data["stop_loss_ratio"], stoploss_order_id=data["stoploss_order_id"], - stoploss_last_update=(datetime.fromtimestamp(data["stoploss_last_update"] // 1000, - tz=timezone.utc) if data["stoploss_last_update"] else None), + stoploss_last_update=( + datetime.fromtimestamp(data["stoploss_last_update_timestamp"] // 1000, + tz=timezone.utc) + if data["stoploss_last_update_timestamp"] else None), initial_stop_loss=data["initial_stop_loss_abs"], initial_stop_loss_pct=data["initial_stop_loss_ratio"], min_rate=data["min_rate"], diff --git a/tests/persistence/test_trade_fromjson.py b/tests/persistence/test_trade_fromjson.py index 529008e02..22053463d 100644 --- a/tests/persistence/test_trade_fromjson.py +++ b/tests/persistence/test_trade_fromjson.py @@ -50,8 +50,8 @@ def test_trade_fromjson(): "stop_loss_ratio": -0.216, "stop_loss_pct": -21.6, "stoploss_order_id": null, - "stoploss_last_update": null, - "stoploss_last_update_timestamp": null, + "stoploss_last_update": "2022-10-18 09:13:42", + "stoploss_last_update_timestamp": 1666077222000, "initial_stop_loss_abs": 0.1981, "initial_stop_loss_ratio": -0.216, "initial_stop_loss_pct": -21.6,