2021-03-23 08:02:32 +00:00
|
|
|
"""
|
|
|
|
IHyperStrategy interface, hyperoptable Parameter class.
|
|
|
|
This module defines a base class for auto-hyperoptable strategies.
|
|
|
|
"""
|
2024-05-12 14:41:08 +00:00
|
|
|
|
2021-03-26 12:25:49 +00:00
|
|
|
import logging
|
2021-05-29 14:37:19 +00:00
|
|
|
from pathlib import Path
|
2023-01-21 14:01:56 +00:00
|
|
|
from typing import Any, Dict, Iterator, List, Optional, Tuple, Type, Union
|
2021-03-23 08:02:32 +00:00
|
|
|
|
2022-09-18 11:20:36 +00:00
|
|
|
from freqtrade.constants import Config
|
2021-03-24 08:32:34 +00:00
|
|
|
from freqtrade.exceptions import OperationalException
|
2023-04-04 18:04:28 +00:00
|
|
|
from freqtrade.misc import deep_merge_dicts
|
2022-05-23 18:18:09 +00:00
|
|
|
from freqtrade.optimize.hyperopt_tools import HyperoptTools
|
|
|
|
from freqtrade.strategy.parameters import BaseParameter
|
2021-03-23 08:02:32 +00:00
|
|
|
|
|
|
|
|
2021-03-26 12:25:49 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2021-11-11 11:06:18 +00:00
|
|
|
class HyperStrategyMixin:
|
2021-03-23 08:02:32 +00:00
|
|
|
"""
|
2021-06-25 13:45:49 +00:00
|
|
|
A helper base class which allows HyperOptAuto class to reuse implementations of buy/sell
|
2021-03-24 08:32:34 +00:00
|
|
|
strategy logic.
|
2021-03-23 08:02:32 +00:00
|
|
|
"""
|
|
|
|
|
2022-09-18 11:20:36 +00:00
|
|
|
def __init__(self, config: Config, *args, **kwargs):
|
2021-03-24 08:32:34 +00:00
|
|
|
"""
|
|
|
|
Initialize hyperoptable strategy mixin.
|
|
|
|
"""
|
2021-05-01 14:36:53 +00:00
|
|
|
self.config = config
|
2021-05-02 08:45:21 +00:00
|
|
|
self.ft_buy_params: List[BaseParameter] = []
|
|
|
|
self.ft_sell_params: List[BaseParameter] = []
|
2021-08-03 05:10:04 +00:00
|
|
|
self.ft_protection_params: List[BaseParameter] = []
|
2021-05-02 08:45:21 +00:00
|
|
|
|
2022-05-29 13:58:40 +00:00
|
|
|
params = self.load_params_from_file()
|
2024-05-12 14:41:08 +00:00
|
|
|
params = params.get("params", {})
|
2022-05-29 13:58:40 +00:00
|
|
|
self._ft_params_from_file = params
|
2022-05-30 05:07:47 +00:00
|
|
|
# Init/loading of parameters is done as part of ft_bot_start().
|
2021-03-23 08:02:32 +00:00
|
|
|
|
2023-01-21 14:01:56 +00:00
|
|
|
def enumerate_parameters(
|
2024-05-12 14:41:08 +00:00
|
|
|
self, category: Optional[str] = None
|
|
|
|
) -> Iterator[Tuple[str, BaseParameter]]:
|
2021-03-23 08:02:32 +00:00
|
|
|
"""
|
2021-06-25 13:45:49 +00:00
|
|
|
Find all optimizable parameters and return (name, attr) iterator.
|
2021-03-23 08:02:32 +00:00
|
|
|
:param category:
|
|
|
|
:return:
|
|
|
|
"""
|
2024-05-12 14:41:08 +00:00
|
|
|
if category not in ("buy", "sell", "protection", None):
|
2021-08-04 18:01:28 +00:00
|
|
|
raise OperationalException(
|
2024-05-12 14:41:08 +00:00
|
|
|
'Category must be one of: "buy", "sell", "protection", None.'
|
|
|
|
)
|
2021-05-02 08:45:21 +00:00
|
|
|
|
|
|
|
if category is None:
|
2021-08-03 05:10:04 +00:00
|
|
|
params = self.ft_buy_params + self.ft_sell_params + self.ft_protection_params
|
2021-05-02 08:45:21 +00:00
|
|
|
else:
|
|
|
|
params = getattr(self, f"ft_{category}_params")
|
|
|
|
|
|
|
|
for par in params:
|
|
|
|
yield par.name, par
|
|
|
|
|
2021-05-29 11:02:18 +00:00
|
|
|
@classmethod
|
|
|
|
def detect_all_parameters(cls) -> Dict:
|
2024-05-12 14:41:08 +00:00
|
|
|
"""Detect all parameters and return them as a list"""
|
2022-05-25 18:43:43 +00:00
|
|
|
params: Dict[str, Any] = {
|
2024-05-12 14:41:08 +00:00
|
|
|
"buy": list(detect_parameters(cls, "buy")),
|
|
|
|
"sell": list(detect_parameters(cls, "sell")),
|
|
|
|
"protection": list(detect_parameters(cls, "protection")),
|
2021-05-29 11:02:18 +00:00
|
|
|
}
|
2024-05-12 14:41:08 +00:00
|
|
|
params.update({"count": len(params["buy"] + params["sell"] + params["protection"])})
|
2021-05-29 11:02:18 +00:00
|
|
|
|
|
|
|
return params
|
|
|
|
|
2022-05-30 04:52:44 +00:00
|
|
|
def ft_load_params_from_file(self) -> None:
|
2022-05-30 04:32:35 +00:00
|
|
|
"""
|
|
|
|
Load Parameters from parameter file
|
|
|
|
Should/must run before config values are loaded in strategy_resolver.
|
|
|
|
"""
|
2022-05-29 14:39:47 +00:00
|
|
|
if self._ft_params_from_file:
|
|
|
|
# Set parameters from Hyperopt results file
|
|
|
|
params = self._ft_params_from_file
|
2024-05-12 14:41:08 +00:00
|
|
|
self.minimal_roi = params.get("roi", getattr(self, "minimal_roi", {}))
|
|
|
|
|
|
|
|
self.stoploss = params.get("stoploss", {}).get(
|
|
|
|
"stoploss", getattr(self, "stoploss", -0.1)
|
|
|
|
)
|
|
|
|
self.max_open_trades = params.get("max_open_trades", {}).get(
|
|
|
|
"max_open_trades", getattr(self, "max_open_trades", -1)
|
|
|
|
)
|
|
|
|
trailing = params.get("trailing", {})
|
2022-05-29 14:39:47 +00:00
|
|
|
self.trailing_stop = trailing.get(
|
2024-05-12 14:41:08 +00:00
|
|
|
"trailing_stop", getattr(self, "trailing_stop", False)
|
|
|
|
)
|
2022-05-29 14:39:47 +00:00
|
|
|
self.trailing_stop_positive = trailing.get(
|
2024-05-12 14:41:08 +00:00
|
|
|
"trailing_stop_positive", getattr(self, "trailing_stop_positive", None)
|
|
|
|
)
|
2022-05-29 14:39:47 +00:00
|
|
|
self.trailing_stop_positive_offset = trailing.get(
|
2024-05-12 14:41:08 +00:00
|
|
|
"trailing_stop_positive_offset", getattr(self, "trailing_stop_positive_offset", 0)
|
|
|
|
)
|
2022-05-29 14:39:47 +00:00
|
|
|
self.trailing_only_offset_is_reached = trailing.get(
|
2024-05-12 14:41:08 +00:00
|
|
|
"trailing_only_offset_is_reached",
|
|
|
|
getattr(self, "trailing_only_offset_is_reached", 0.0),
|
|
|
|
)
|
2022-05-29 14:39:47 +00:00
|
|
|
|
2022-05-29 13:58:40 +00:00
|
|
|
def ft_load_hyper_params(self, hyperopt: bool = False) -> None:
|
2021-04-24 05:00:33 +00:00
|
|
|
"""
|
|
|
|
Load Hyperoptable parameters
|
2022-05-29 13:58:40 +00:00
|
|
|
Prevalence:
|
|
|
|
* Parameters from parameter file
|
|
|
|
* Parameters defined in parameters objects (buy_params, sell_params, ...)
|
|
|
|
* Parameter defaults
|
2021-04-24 05:00:33 +00:00
|
|
|
"""
|
2022-05-29 13:58:40 +00:00
|
|
|
|
2024-05-12 14:41:08 +00:00
|
|
|
buy_params = deep_merge_dicts(
|
|
|
|
self._ft_params_from_file.get("buy", {}), getattr(self, "buy_params", {})
|
|
|
|
)
|
|
|
|
sell_params = deep_merge_dicts(
|
|
|
|
self._ft_params_from_file.get("sell", {}), getattr(self, "sell_params", {})
|
|
|
|
)
|
|
|
|
protection_params = deep_merge_dicts(
|
|
|
|
self._ft_params_from_file.get("protection", {}), getattr(self, "protection_params", {})
|
|
|
|
)
|
2021-04-24 05:00:33 +00:00
|
|
|
|
2024-05-12 14:41:08 +00:00
|
|
|
self._ft_load_params(buy_params, "buy", hyperopt)
|
|
|
|
self._ft_load_params(sell_params, "sell", hyperopt)
|
|
|
|
self._ft_load_params(protection_params, "protection", hyperopt)
|
2021-05-29 14:37:19 +00:00
|
|
|
|
|
|
|
def load_params_from_file(self) -> Dict:
|
2024-05-12 14:41:08 +00:00
|
|
|
filename_str = getattr(self, "__file__", "")
|
2021-05-29 14:37:19 +00:00
|
|
|
if not filename_str:
|
|
|
|
return {}
|
2024-05-12 14:41:08 +00:00
|
|
|
filename = Path(filename_str).with_suffix(".json")
|
2021-05-29 14:37:19 +00:00
|
|
|
|
|
|
|
if filename.is_file():
|
|
|
|
logger.info(f"Loading parameters from file {filename}")
|
2021-06-29 18:38:14 +00:00
|
|
|
try:
|
2023-04-04 18:04:28 +00:00
|
|
|
params = HyperoptTools.load_params(filename)
|
2024-05-12 14:41:08 +00:00
|
|
|
if params.get("strategy_name") != self.__class__.__name__:
|
|
|
|
raise OperationalException("Invalid parameter file provided.")
|
2021-06-29 18:38:14 +00:00
|
|
|
return params
|
|
|
|
except ValueError:
|
2021-06-30 04:43:49 +00:00
|
|
|
logger.warning("Invalid parameter file format.")
|
2021-06-29 18:38:14 +00:00
|
|
|
return {}
|
2021-05-29 14:37:19 +00:00
|
|
|
logger.info("Found no parameter file.")
|
|
|
|
|
|
|
|
return {}
|
|
|
|
|
2022-05-29 13:58:40 +00:00
|
|
|
def _ft_load_params(self, params: Dict, space: str, hyperopt: bool = False) -> None:
|
2021-03-23 08:02:32 +00:00
|
|
|
"""
|
2021-06-25 13:45:49 +00:00
|
|
|
Set optimizable parameter values.
|
2021-03-23 08:02:32 +00:00
|
|
|
:param params: Dictionary with new parameter values.
|
|
|
|
"""
|
|
|
|
if not params:
|
2021-04-23 18:35:30 +00:00
|
|
|
logger.info(f"No params for {space} found, using default values.")
|
2021-05-02 08:45:21 +00:00
|
|
|
param_container: List[BaseParameter] = getattr(self, f"ft_{space}_params")
|
2021-04-23 18:35:30 +00:00
|
|
|
|
2022-05-30 05:22:16 +00:00
|
|
|
for attr_name, attr in detect_parameters(self, space):
|
2021-05-02 08:45:21 +00:00
|
|
|
attr.name = attr_name
|
2021-05-01 14:36:53 +00:00
|
|
|
attr.in_space = hyperopt and HyperoptTools.has_space(self.config, space)
|
2021-05-02 08:45:21 +00:00
|
|
|
if not attr.category:
|
|
|
|
attr.category = space
|
|
|
|
|
|
|
|
param_container.append(attr)
|
|
|
|
|
2021-04-23 18:35:30 +00:00
|
|
|
if params and attr_name in params:
|
2021-03-31 09:31:28 +00:00
|
|
|
if attr.load:
|
2021-03-26 12:25:49 +00:00
|
|
|
attr.value = params[attr_name]
|
2024-05-12 14:41:08 +00:00
|
|
|
logger.info(f"Strategy Parameter: {attr_name} = {attr.value}")
|
2021-03-26 12:25:49 +00:00
|
|
|
else:
|
2024-05-12 14:41:08 +00:00
|
|
|
logger.warning(
|
|
|
|
f'Parameter "{attr_name}" exists, but is disabled. '
|
|
|
|
f'Default value "{attr.value}" used.'
|
|
|
|
)
|
2021-04-23 18:35:30 +00:00
|
|
|
else:
|
2024-05-12 14:41:08 +00:00
|
|
|
logger.info(f"Strategy Parameter(default): {attr_name} = {attr.value}")
|
2021-05-02 08:45:21 +00:00
|
|
|
|
2023-02-13 19:13:26 +00:00
|
|
|
def get_no_optimize_params(self) -> Dict[str, Dict]:
|
2021-05-02 08:45:21 +00:00
|
|
|
"""
|
|
|
|
Returns list of Parameters that are not part of the current optimize job
|
|
|
|
"""
|
2022-05-25 18:43:43 +00:00
|
|
|
params: Dict[str, Dict] = {
|
2024-05-12 14:41:08 +00:00
|
|
|
"buy": {},
|
|
|
|
"sell": {},
|
|
|
|
"protection": {},
|
2021-05-02 08:45:21 +00:00
|
|
|
}
|
|
|
|
for name, p in self.enumerate_parameters():
|
2023-02-13 19:13:26 +00:00
|
|
|
if p.category and (not p.optimize or not p.in_space):
|
2021-05-02 08:45:21 +00:00
|
|
|
params[p.category][name] = p.value
|
|
|
|
return params
|
2022-05-30 05:22:16 +00:00
|
|
|
|
|
|
|
|
|
|
|
def detect_parameters(
|
2024-05-12 14:41:08 +00:00
|
|
|
obj: Union[HyperStrategyMixin, Type[HyperStrategyMixin]], category: str
|
|
|
|
) -> Iterator[Tuple[str, BaseParameter]]:
|
2022-05-30 05:22:16 +00:00
|
|
|
"""
|
|
|
|
Detect all parameters for 'category' for "obj"
|
|
|
|
:param obj: Strategy object or class
|
|
|
|
:param category: category - usually `'buy', 'sell', 'protection',...
|
|
|
|
"""
|
|
|
|
for attr_name in dir(obj):
|
2024-05-12 14:41:08 +00:00
|
|
|
if not attr_name.startswith("__"): # Ignore internals, not strictly necessary.
|
2022-05-30 05:22:16 +00:00
|
|
|
attr = getattr(obj, attr_name)
|
|
|
|
if issubclass(attr.__class__, BaseParameter):
|
2024-05-12 14:41:08 +00:00
|
|
|
if (
|
|
|
|
attr_name.startswith(category + "_")
|
|
|
|
and attr.category is not None
|
|
|
|
and attr.category != category
|
|
|
|
):
|
2022-05-30 05:22:16 +00:00
|
|
|
raise OperationalException(
|
2024-05-12 14:41:08 +00:00
|
|
|
f"Inconclusive parameter name {attr_name}, category: {attr.category}."
|
|
|
|
)
|
2022-07-11 06:14:39 +00:00
|
|
|
|
2024-05-12 14:41:08 +00:00
|
|
|
if category == attr.category or (
|
|
|
|
attr_name.startswith(category + "_") and attr.category is None
|
|
|
|
):
|
2022-05-30 05:22:16 +00:00
|
|
|
yield attr_name, attr
|