Merge branch 'develop' into logging-syslog
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
from freqtrade.configuration.arguments import Arguments # noqa: F401
|
||||
from freqtrade.configuration.check_exchange import check_exchange, remove_credentials # noqa: F401
|
||||
from freqtrade.configuration.timerange import TimeRange # noqa: F401
|
||||
from freqtrade.configuration.configuration import Configuration # noqa: F401
|
||||
from freqtrade.configuration.config_validation import validate_config_consistency # noqa: F401
|
||||
|
@@ -13,7 +13,7 @@ ARGS_COMMON = ["verbosity", "logfile", "version", "config", "datadir", "user_dat
|
||||
|
||||
ARGS_STRATEGY = ["strategy", "strategy_path"]
|
||||
|
||||
ARGS_MAIN = ARGS_COMMON + ARGS_STRATEGY + ["db_url", "sd_notify"]
|
||||
ARGS_TRADE = ["db_url", "sd_notify", "dry_run"]
|
||||
|
||||
ARGS_COMMON_OPTIMIZE = ["ticker_interval", "timerange",
|
||||
"max_open_trades", "stake_amount", "fee"]
|
||||
@@ -37,13 +37,18 @@ ARGS_LIST_TIMEFRAMES = ["exchange", "print_one_column"]
|
||||
ARGS_LIST_PAIRS = ["exchange", "print_list", "list_pairs_print_json", "print_one_column",
|
||||
"print_csv", "base_currencies", "quote_currencies", "list_pairs_all"]
|
||||
|
||||
ARGS_CREATE_USERDIR = ["user_data_dir"]
|
||||
ARGS_CREATE_USERDIR = ["user_data_dir", "reset"]
|
||||
|
||||
ARGS_BUILD_STRATEGY = ["user_data_dir", "strategy", "template"]
|
||||
|
||||
ARGS_BUILD_HYPEROPT = ["user_data_dir", "hyperopt", "template"]
|
||||
|
||||
ARGS_DOWNLOAD_DATA = ["pairs", "pairs_file", "days", "download_trades", "exchange",
|
||||
"timeframes", "erase"]
|
||||
|
||||
ARGS_PLOT_DATAFRAME = ["pairs", "indicators1", "indicators2", "plot_limit", "db_url",
|
||||
"trade_source", "export", "exportfilename", "timerange", "ticker_interval"]
|
||||
ARGS_PLOT_DATAFRAME = ["pairs", "indicators1", "indicators2", "plot_limit",
|
||||
"db_url", "trade_source", "export", "exportfilename",
|
||||
"timerange", "ticker_interval"]
|
||||
|
||||
ARGS_PLOT_PROFIT = ["pairs", "timerange", "export", "exportfilename", "db_url",
|
||||
"trade_source", "ticker_interval"]
|
||||
@@ -51,7 +56,7 @@ ARGS_PLOT_PROFIT = ["pairs", "timerange", "export", "exportfilename", "db_url",
|
||||
NO_CONF_REQURIED = ["download-data", "list-timeframes", "list-markets", "list-pairs",
|
||||
"plot-dataframe", "plot-profit"]
|
||||
|
||||
NO_CONF_ALLOWED = ["create-userdir", "list-exchanges"]
|
||||
NO_CONF_ALLOWED = ["create-userdir", "list-exchanges", "new-hyperopt", "new-strategy"]
|
||||
|
||||
|
||||
class Arguments:
|
||||
@@ -61,11 +66,6 @@ class Arguments:
|
||||
def __init__(self, args: Optional[List[str]]) -> None:
|
||||
self.args = args
|
||||
self._parsed_arg: Optional[argparse.Namespace] = None
|
||||
self.parser = argparse.ArgumentParser(description='Free, open source crypto trading bot')
|
||||
|
||||
def _load_args(self) -> None:
|
||||
self._build_args(optionlist=ARGS_MAIN)
|
||||
self._build_subcommands()
|
||||
|
||||
def get_parsed_arg(self) -> Dict[str, Any]:
|
||||
"""
|
||||
@@ -73,7 +73,7 @@ class Arguments:
|
||||
:return: List[str] List of arguments
|
||||
"""
|
||||
if self._parsed_arg is None:
|
||||
self._load_args()
|
||||
self._build_subcommands()
|
||||
self._parsed_arg = self._parse_args()
|
||||
|
||||
return vars(self._parsed_arg)
|
||||
@@ -84,22 +84,17 @@ class Arguments:
|
||||
"""
|
||||
parsed_arg = self.parser.parse_args(self.args)
|
||||
|
||||
# When no config is provided, but a config exists, use that configuration!
|
||||
subparser = parsed_arg.subparser if 'subparser' in parsed_arg else None
|
||||
|
||||
# Workaround issue in argparse with action='append' and default value
|
||||
# (see https://bugs.python.org/issue16399)
|
||||
# Allow no-config for certain commands (like downloading / plotting)
|
||||
if (parsed_arg.config is None
|
||||
and subparser not in NO_CONF_ALLOWED
|
||||
and ((Path.cwd() / constants.DEFAULT_CONFIG).is_file()
|
||||
or (subparser not in NO_CONF_REQURIED))):
|
||||
if ('config' in parsed_arg and parsed_arg.config is None and
|
||||
((Path.cwd() / constants.DEFAULT_CONFIG).is_file() or
|
||||
not ('command' in parsed_arg and parsed_arg.command in NO_CONF_REQURIED))):
|
||||
parsed_arg.config = [constants.DEFAULT_CONFIG]
|
||||
|
||||
return parsed_arg
|
||||
|
||||
def _build_args(self, optionlist, parser=None):
|
||||
parser = parser or self.parser
|
||||
def _build_args(self, optionlist, parser):
|
||||
|
||||
for val in optionlist:
|
||||
opt = AVAILABLE_CLI_OPTIONS[val]
|
||||
@@ -110,38 +105,81 @@ class Arguments:
|
||||
Builds and attaches all subcommands.
|
||||
:return: None
|
||||
"""
|
||||
# Build shared arguments (as group Common Options)
|
||||
_common_parser = argparse.ArgumentParser(add_help=False)
|
||||
group = _common_parser.add_argument_group("Common arguments")
|
||||
self._build_args(optionlist=ARGS_COMMON, parser=group)
|
||||
|
||||
_strategy_parser = argparse.ArgumentParser(add_help=False)
|
||||
strategy_group = _strategy_parser.add_argument_group("Strategy arguments")
|
||||
self._build_args(optionlist=ARGS_STRATEGY, parser=strategy_group)
|
||||
|
||||
# Build main command
|
||||
self.parser = argparse.ArgumentParser(description='Free, open source crypto trading bot')
|
||||
self._build_args(optionlist=['version'], parser=self.parser)
|
||||
|
||||
from freqtrade.optimize import start_backtesting, start_hyperopt, start_edge
|
||||
from freqtrade.utils import (start_create_userdir, start_download_data,
|
||||
start_list_exchanges, start_list_timeframes,
|
||||
start_list_markets)
|
||||
start_list_exchanges, start_list_markets,
|
||||
start_new_hyperopt, start_new_strategy,
|
||||
start_list_timeframes, start_trading)
|
||||
from freqtrade.plot.plot_utils import start_plot_dataframe, start_plot_profit
|
||||
|
||||
subparsers = self.parser.add_subparsers(dest='subparser')
|
||||
subparsers = self.parser.add_subparsers(dest='command',
|
||||
# Use custom message when no subhandler is added
|
||||
# shown from `main.py`
|
||||
# required=True
|
||||
)
|
||||
|
||||
# Add trade subcommand
|
||||
trade_cmd = subparsers.add_parser('trade', help='Trade module.',
|
||||
parents=[_common_parser, _strategy_parser])
|
||||
trade_cmd.set_defaults(func=start_trading)
|
||||
self._build_args(optionlist=ARGS_TRADE, parser=trade_cmd)
|
||||
|
||||
# Add backtesting subcommand
|
||||
backtesting_cmd = subparsers.add_parser('backtesting', help='Backtesting module.')
|
||||
backtesting_cmd = subparsers.add_parser('backtesting', help='Backtesting module.',
|
||||
parents=[_common_parser, _strategy_parser])
|
||||
backtesting_cmd.set_defaults(func=start_backtesting)
|
||||
self._build_args(optionlist=ARGS_BACKTEST, parser=backtesting_cmd)
|
||||
|
||||
# Add edge subcommand
|
||||
edge_cmd = subparsers.add_parser('edge', help='Edge module.')
|
||||
edge_cmd = subparsers.add_parser('edge', help='Edge module.',
|
||||
parents=[_common_parser, _strategy_parser])
|
||||
edge_cmd.set_defaults(func=start_edge)
|
||||
self._build_args(optionlist=ARGS_EDGE, parser=edge_cmd)
|
||||
|
||||
# Add hyperopt subcommand
|
||||
hyperopt_cmd = subparsers.add_parser('hyperopt', help='Hyperopt module.')
|
||||
hyperopt_cmd = subparsers.add_parser('hyperopt', help='Hyperopt module.',
|
||||
parents=[_common_parser, _strategy_parser],
|
||||
)
|
||||
hyperopt_cmd.set_defaults(func=start_hyperopt)
|
||||
self._build_args(optionlist=ARGS_HYPEROPT, parser=hyperopt_cmd)
|
||||
|
||||
# add create-userdir subcommand
|
||||
create_userdir_cmd = subparsers.add_parser('create-userdir',
|
||||
help="Create user-data directory.")
|
||||
help="Create user-data directory.",
|
||||
)
|
||||
create_userdir_cmd.set_defaults(func=start_create_userdir)
|
||||
self._build_args(optionlist=ARGS_CREATE_USERDIR, parser=create_userdir_cmd)
|
||||
|
||||
# add new-strategy subcommand
|
||||
build_strategy_cmd = subparsers.add_parser('new-strategy',
|
||||
help="Create new strategy")
|
||||
build_strategy_cmd.set_defaults(func=start_new_strategy)
|
||||
self._build_args(optionlist=ARGS_BUILD_STRATEGY, parser=build_strategy_cmd)
|
||||
|
||||
# add new-hyperopt subcommand
|
||||
build_hyperopt_cmd = subparsers.add_parser('new-hyperopt',
|
||||
help="Create new hyperopt")
|
||||
build_hyperopt_cmd.set_defaults(func=start_new_hyperopt)
|
||||
self._build_args(optionlist=ARGS_BUILD_HYPEROPT, parser=build_hyperopt_cmd)
|
||||
|
||||
# Add list-exchanges subcommand
|
||||
list_exchanges_cmd = subparsers.add_parser(
|
||||
'list-exchanges',
|
||||
help='Print available exchanges.'
|
||||
help='Print available exchanges.',
|
||||
parents=[_common_parser],
|
||||
)
|
||||
list_exchanges_cmd.set_defaults(func=start_list_exchanges)
|
||||
self._build_args(optionlist=ARGS_LIST_EXCHANGES, parser=list_exchanges_cmd)
|
||||
@@ -149,7 +187,8 @@ class Arguments:
|
||||
# Add list-timeframes subcommand
|
||||
list_timeframes_cmd = subparsers.add_parser(
|
||||
'list-timeframes',
|
||||
help='Print available ticker intervals (timeframes) for the exchange.'
|
||||
help='Print available ticker intervals (timeframes) for the exchange.',
|
||||
parents=[_common_parser],
|
||||
)
|
||||
list_timeframes_cmd.set_defaults(func=start_list_timeframes)
|
||||
self._build_args(optionlist=ARGS_LIST_TIMEFRAMES, parser=list_timeframes_cmd)
|
||||
@@ -157,7 +196,8 @@ class Arguments:
|
||||
# Add list-markets subcommand
|
||||
list_markets_cmd = subparsers.add_parser(
|
||||
'list-markets',
|
||||
help='Print markets on exchange.'
|
||||
help='Print markets on exchange.',
|
||||
parents=[_common_parser],
|
||||
)
|
||||
list_markets_cmd.set_defaults(func=partial(start_list_markets, pairs_only=False))
|
||||
self._build_args(optionlist=ARGS_LIST_PAIRS, parser=list_markets_cmd)
|
||||
@@ -165,7 +205,8 @@ class Arguments:
|
||||
# Add list-pairs subcommand
|
||||
list_pairs_cmd = subparsers.add_parser(
|
||||
'list-pairs',
|
||||
help='Print pairs on exchange.'
|
||||
help='Print pairs on exchange.',
|
||||
parents=[_common_parser],
|
||||
)
|
||||
list_pairs_cmd.set_defaults(func=partial(start_list_markets, pairs_only=True))
|
||||
self._build_args(optionlist=ARGS_LIST_PAIRS, parser=list_pairs_cmd)
|
||||
@@ -173,16 +214,17 @@ class Arguments:
|
||||
# Add download-data subcommand
|
||||
download_data_cmd = subparsers.add_parser(
|
||||
'download-data',
|
||||
help='Download backtesting data.'
|
||||
help='Download backtesting data.',
|
||||
parents=[_common_parser],
|
||||
)
|
||||
download_data_cmd.set_defaults(func=start_download_data)
|
||||
self._build_args(optionlist=ARGS_DOWNLOAD_DATA, parser=download_data_cmd)
|
||||
|
||||
# Add Plotting subcommand
|
||||
from freqtrade.plot.plot_utils import start_plot_dataframe, start_plot_profit
|
||||
plot_dataframe_cmd = subparsers.add_parser(
|
||||
'plot-dataframe',
|
||||
help='Plot candles with indicators.'
|
||||
help='Plot candles with indicators.',
|
||||
parents=[_common_parser, _strategy_parser],
|
||||
)
|
||||
plot_dataframe_cmd.set_defaults(func=start_plot_dataframe)
|
||||
self._build_args(optionlist=ARGS_PLOT_DATAFRAME, parser=plot_dataframe_cmd)
|
||||
@@ -190,7 +232,8 @@ class Arguments:
|
||||
# Plot profit
|
||||
plot_profit_cmd = subparsers.add_parser(
|
||||
'plot-profit',
|
||||
help='Generate plot showing profits.'
|
||||
help='Generate plot showing profits.',
|
||||
parents=[_common_parser],
|
||||
)
|
||||
plot_profit_cmd.set_defaults(func=start_plot_profit)
|
||||
self._build_args(optionlist=ARGS_PLOT_PROFIT, parser=plot_profit_cmd)
|
||||
|
@@ -10,6 +10,19 @@ from freqtrade.state import RunMode
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def remove_credentials(config: Dict[str, Any]):
|
||||
"""
|
||||
Removes exchange keys from the configuration and specifies dry-run
|
||||
Used for backtesting / hyperopt / edge and utils.
|
||||
Modifies the input dict!
|
||||
"""
|
||||
config['exchange']['key'] = ''
|
||||
config['exchange']['secret'] = ''
|
||||
config['exchange']['password'] = ''
|
||||
config['exchange']['uid'] = ''
|
||||
config['dry_run'] = True
|
||||
|
||||
|
||||
def check_exchange(config: Dict[str, Any], check_for_bad: bool = True) -> bool:
|
||||
"""
|
||||
Check if the exchange name in the config file is supported by Freqtrade
|
||||
@@ -21,7 +34,8 @@ def check_exchange(config: Dict[str, Any], check_for_bad: bool = True) -> bool:
|
||||
and thus is not known for the Freqtrade at all.
|
||||
"""
|
||||
|
||||
if config['runmode'] in [RunMode.PLOT] and not config.get('exchange', {}).get('name'):
|
||||
if (config['runmode'] in [RunMode.PLOT, RunMode.UTIL_NO_EXCHANGE, RunMode.OTHER]
|
||||
and not config.get('exchange', {}).get('name')):
|
||||
# Skip checking exchange in plot mode, since it requires no exchange
|
||||
return True
|
||||
logger.info("Checking exchange...")
|
||||
|
@@ -63,12 +63,16 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
help='Path to userdata directory.',
|
||||
metavar='PATH',
|
||||
),
|
||||
"reset": Arg(
|
||||
'--reset',
|
||||
help='Reset sample files to their original state.',
|
||||
action='store_true',
|
||||
),
|
||||
# Main options
|
||||
"strategy": Arg(
|
||||
'-s', '--strategy',
|
||||
help='Specify strategy class name (default: `%(default)s`).',
|
||||
help='Specify strategy class name which will be used by the bot.',
|
||||
metavar='NAME',
|
||||
default='DefaultStrategy',
|
||||
),
|
||||
"strategy_path": Arg(
|
||||
'--strategy-path',
|
||||
@@ -87,6 +91,11 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
help='Notify systemd service manager.',
|
||||
action='store_true',
|
||||
),
|
||||
"dry_run": Arg(
|
||||
'--dry-run',
|
||||
help='Enforce dry-run for trading (removes Exchange secrets and simulates trades).',
|
||||
action='store_true',
|
||||
),
|
||||
# Optimize common
|
||||
"ticker_interval": Arg(
|
||||
'-i', '--ticker-interval',
|
||||
@@ -137,7 +146,7 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
),
|
||||
"exportfilename": Arg(
|
||||
'--export-filename',
|
||||
help='Save backtest results to the file with this filename (default: `%(default)s`). '
|
||||
help='Save backtest results to the file with this filename. '
|
||||
'Requires `--export` to be set as well. '
|
||||
'Example: `--export-filename=user_data/backtest_results/backtest_today.json`',
|
||||
metavar='PATH',
|
||||
@@ -157,14 +166,13 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
),
|
||||
# Hyperopt
|
||||
"hyperopt": Arg(
|
||||
'--customhyperopt',
|
||||
help='Specify hyperopt class name (default: `%(default)s`).',
|
||||
'--hyperopt',
|
||||
help='Specify hyperopt class name which will be used by the bot.',
|
||||
metavar='NAME',
|
||||
default=constants.DEFAULT_HYPEROPT,
|
||||
),
|
||||
"hyperopt_path": Arg(
|
||||
'--hyperopt-path',
|
||||
help='Specify additional lookup path for Hyperopts and Hyperopt Loss functions.',
|
||||
help='Specify additional lookup path for Hyperopt and Hyperopt Loss functions.',
|
||||
metavar='PATH',
|
||||
),
|
||||
"epochs": Arg(
|
||||
@@ -175,7 +183,7 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
default=constants.HYPEROPT_EPOCH,
|
||||
),
|
||||
"spaces": Arg(
|
||||
'-s', '--spaces',
|
||||
'--spaces',
|
||||
help='Specify which parameters to hyperopt. Space-separated list. '
|
||||
'Default: `%(default)s`.',
|
||||
choices=['all', 'buy', 'sell', 'roi', 'stoploss'],
|
||||
@@ -332,6 +340,14 @@ AVAILABLE_CLI_OPTIONS = {
|
||||
help='Clean all existing data for the selected exchange/pairs/timeframes.',
|
||||
action='store_true',
|
||||
),
|
||||
# Templating options
|
||||
"template": Arg(
|
||||
'--template',
|
||||
help='Use a template which is either `minimal` or '
|
||||
'`full` (containing multiple sample indicators). Default: `%(default)s`.',
|
||||
choices=['full', 'minimal'],
|
||||
default='full',
|
||||
),
|
||||
# Plot dataframe
|
||||
"indicators1": Arg(
|
||||
'--indicators1',
|
||||
|
@@ -5,7 +5,7 @@ from jsonschema import Draft4Validator, validators
|
||||
from jsonschema.exceptions import ValidationError, best_match
|
||||
|
||||
from freqtrade import constants, OperationalException
|
||||
|
||||
from freqtrade.state import RunMode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -61,9 +61,15 @@ def validate_config_consistency(conf: Dict[str, Any]) -> None:
|
||||
:param conf: Config in JSON format
|
||||
:return: Returns None if everything is ok, otherwise throw an OperationalException
|
||||
"""
|
||||
|
||||
# validating trailing stoploss
|
||||
_validate_trailing_stoploss(conf)
|
||||
_validate_edge(conf)
|
||||
_validate_whitelist(conf)
|
||||
|
||||
# validate configuration before returning
|
||||
logger.info('Validating configuration ...')
|
||||
validate_config_schema(conf)
|
||||
|
||||
|
||||
def _validate_trailing_stoploss(conf: Dict[str, Any]) -> None:
|
||||
@@ -111,3 +117,17 @@ def _validate_edge(conf: Dict[str, Any]) -> None:
|
||||
"Edge and VolumePairList are incompatible, "
|
||||
"Edge will override whatever pairs VolumePairlist selects."
|
||||
)
|
||||
|
||||
|
||||
def _validate_whitelist(conf: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Dynamic whitelist does not require pair_whitelist to be set - however StaticWhitelist does.
|
||||
"""
|
||||
if conf.get('runmode', RunMode.OTHER) in [RunMode.OTHER, RunMode.PLOT,
|
||||
RunMode.UTIL_NO_EXCHANGE, RunMode.UTIL_EXCHANGE]:
|
||||
return
|
||||
|
||||
for pl in conf.get('pairlists', [{'method': 'StaticPairList'}]):
|
||||
if (pl.get('method') == 'StaticPairList'
|
||||
and not conf.get('exchange', {}).get('pair_whitelist')):
|
||||
raise OperationalException("StaticPairList requires pair_whitelist to be set.")
|
||||
|
@@ -9,15 +9,13 @@ from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
from freqtrade import OperationalException, constants
|
||||
from freqtrade.configuration.check_exchange import check_exchange
|
||||
from freqtrade.configuration.config_validation import (validate_config_consistency,
|
||||
validate_config_schema)
|
||||
from freqtrade.configuration.deprecated_settings import process_temporary_deprecated_settings
|
||||
from freqtrade.configuration.directory_operations import (create_datadir,
|
||||
create_userdata_dir)
|
||||
from freqtrade.configuration.load_config import load_config_file
|
||||
from freqtrade.loggers import setup_logging
|
||||
from freqtrade.misc import deep_merge_dicts, json_load
|
||||
from freqtrade.state import RunMode
|
||||
from freqtrade.state import RunMode, TRADING_MODES, NON_UTIL_MODES
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -81,9 +79,8 @@ class Configuration:
|
||||
if 'ask_strategy' not in config:
|
||||
config['ask_strategy'] = {}
|
||||
|
||||
# validate configuration before returning
|
||||
logger.info('Validating configuration ...')
|
||||
validate_config_schema(config)
|
||||
if 'pairlists' not in config:
|
||||
config['pairlists'] = []
|
||||
|
||||
return config
|
||||
|
||||
@@ -93,19 +90,21 @@ class Configuration:
|
||||
:return: Configuration dictionary
|
||||
"""
|
||||
# Load all configs
|
||||
config: Dict[str, Any] = self.load_from_files(self.args["config"])
|
||||
config: Dict[str, Any] = self.load_from_files(self.args.get("config", []))
|
||||
|
||||
# Keep a copy of the original configuration file
|
||||
config['original_config'] = deepcopy(config)
|
||||
|
||||
self._process_runmode(config)
|
||||
|
||||
self._process_common_options(config)
|
||||
|
||||
self._process_trading_options(config)
|
||||
|
||||
self._process_optimize_options(config)
|
||||
|
||||
self._process_plot_options(config)
|
||||
|
||||
self._process_runmode(config)
|
||||
|
||||
# Check if the exchange set by the user is supported
|
||||
check_exchange(config, config.get('experimental', {}).get('block_bad_exchanges', True))
|
||||
|
||||
@@ -113,8 +112,6 @@ class Configuration:
|
||||
|
||||
process_temporary_deprecated_settings(config)
|
||||
|
||||
validate_config_consistency(config)
|
||||
|
||||
return config
|
||||
|
||||
def _process_logging_options(self, config: Dict[str, Any]) -> None:
|
||||
@@ -130,21 +127,9 @@ class Configuration:
|
||||
|
||||
setup_logging(config)
|
||||
|
||||
def _process_common_options(self, config: Dict[str, Any]) -> None:
|
||||
|
||||
self._process_logging_options(config)
|
||||
|
||||
# Set strategy if not specified in config and or if it's non default
|
||||
if self.args.get("strategy") != constants.DEFAULT_STRATEGY or not config.get('strategy'):
|
||||
config.update({'strategy': self.args.get("strategy")})
|
||||
|
||||
self._args_to_config(config, argname='strategy_path',
|
||||
logstring='Using additional Strategy lookup path: {}')
|
||||
|
||||
if ('db_url' in self.args and self.args["db_url"] and
|
||||
self.args["db_url"] != constants.DEFAULT_DB_PROD_URL):
|
||||
config.update({'db_url': self.args["db_url"]})
|
||||
logger.info('Parameter --db-url detected ...')
|
||||
def _process_trading_options(self, config: Dict[str, Any]) -> None:
|
||||
if config['runmode'] not in TRADING_MODES:
|
||||
return
|
||||
|
||||
if config.get('dry_run', False):
|
||||
logger.info('Dry run is enabled')
|
||||
@@ -158,17 +143,33 @@ class Configuration:
|
||||
|
||||
logger.info(f'Using DB: "{config["db_url"]}"')
|
||||
|
||||
def _process_common_options(self, config: Dict[str, Any]) -> None:
|
||||
|
||||
self._process_logging_options(config)
|
||||
|
||||
# Set strategy if not specified in config and or if it's non default
|
||||
if self.args.get("strategy") or not config.get('strategy'):
|
||||
config.update({'strategy': self.args.get("strategy")})
|
||||
|
||||
self._args_to_config(config, argname='strategy_path',
|
||||
logstring='Using additional Strategy lookup path: {}')
|
||||
|
||||
if ('db_url' in self.args and self.args["db_url"] and
|
||||
self.args["db_url"] != constants.DEFAULT_DB_PROD_URL):
|
||||
config.update({'db_url': self.args["db_url"]})
|
||||
logger.info('Parameter --db-url detected ...')
|
||||
|
||||
if config.get('forcebuy_enable', False):
|
||||
logger.warning('`forcebuy` RPC message enabled.')
|
||||
|
||||
# Setting max_open_trades to infinite if -1
|
||||
if config.get('max_open_trades') == -1:
|
||||
config['max_open_trades'] = float('inf')
|
||||
|
||||
# Support for sd_notify
|
||||
if 'sd_notify' in self.args and self.args["sd_notify"]:
|
||||
config['internals'].update({'sd_notify': True})
|
||||
|
||||
self._args_to_config(config, argname='dry_run',
|
||||
logstring='Parameter --dry-run detected, '
|
||||
'overriding dry_run to: {} ...')
|
||||
|
||||
def _process_datadir_options(self, config: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Extract information for sys.argv and load directory configurations
|
||||
@@ -179,6 +180,9 @@ class Configuration:
|
||||
config['exchange']['name'] = self.args["exchange"]
|
||||
logger.info(f"Using exchange {config['exchange']['name']}")
|
||||
|
||||
if 'pair_whitelist' not in config['exchange']:
|
||||
config['exchange']['pair_whitelist'] = []
|
||||
|
||||
if 'user_data_dir' in self.args and self.args["user_data_dir"]:
|
||||
config.update({'user_data_dir': self.args["user_data_dir"]})
|
||||
elif 'user_data_dir' not in config:
|
||||
@@ -209,6 +213,10 @@ class Configuration:
|
||||
self._args_to_config(config, argname='position_stacking',
|
||||
logstring='Parameter --enable-position-stacking detected ...')
|
||||
|
||||
# Setting max_open_trades to infinite if -1
|
||||
if config.get('max_open_trades') == -1:
|
||||
config['max_open_trades'] = float('inf')
|
||||
|
||||
if 'use_max_market_positions' in self.args and not self.args["use_max_market_positions"]:
|
||||
config.update({'use_max_market_positions': False})
|
||||
logger.info('Parameter --disable-max-market-positions detected ...')
|
||||
@@ -217,7 +225,7 @@ class Configuration:
|
||||
config.update({'max_open_trades': self.args["max_open_trades"]})
|
||||
logger.info('Parameter --max_open_trades detected, '
|
||||
'overriding max_open_trades to: %s ...', config.get('max_open_trades'))
|
||||
else:
|
||||
elif config['runmode'] in NON_UTIL_MODES:
|
||||
logger.info('Using max_open_trades: %s ...', config.get('max_open_trades'))
|
||||
|
||||
self._args_to_config(config, argname='stake_amount',
|
||||
|
@@ -57,3 +57,26 @@ def process_temporary_deprecated_settings(config: Dict[str, Any]) -> None:
|
||||
'experimental', 'sell_profit_only')
|
||||
process_deprecated_setting(config, 'ask_strategy', 'ignore_roi_if_buy_signal',
|
||||
'experimental', 'ignore_roi_if_buy_signal')
|
||||
|
||||
if not config.get('pairlists') and not config.get('pairlists'):
|
||||
config['pairlists'] = [{'method': 'StaticPairList'}]
|
||||
logger.warning(
|
||||
"DEPRECATED: "
|
||||
"Pairlists must be defined explicitly in the future."
|
||||
"Defaulting to StaticPairList for now.")
|
||||
|
||||
if config.get('pairlist', {}).get("method") == 'VolumePairList':
|
||||
logger.warning(
|
||||
"DEPRECATED: "
|
||||
f"Using VolumePairList in pairlist is deprecated and must be moved to pairlists. "
|
||||
"Please refer to the docs on configuration details")
|
||||
pl = {'method': 'VolumePairList'}
|
||||
pl.update(config.get('pairlist', {}).get('config'))
|
||||
config['pairlists'].append(pl)
|
||||
|
||||
if config.get('pairlist', {}).get('config', {}).get('precision_filter'):
|
||||
logger.warning(
|
||||
"DEPRECATED: "
|
||||
f"Using precision_filter setting is deprecated and has been replaced by"
|
||||
"PrecisionFilter. Please refer to the docs on configuration details")
|
||||
config['pairlists'].append({'method': 'PrecisionFilter'})
|
||||
|
@@ -1,8 +1,10 @@
|
||||
import logging
|
||||
from typing import Any, Dict, Optional
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from freqtrade import OperationalException
|
||||
from freqtrade.constants import USER_DATA_FILES
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -31,7 +33,8 @@ def create_userdata_dir(directory: str, create_dir=False) -> Path:
|
||||
:param create_dir: Create directory if it does not exist.
|
||||
:return: Path object containing the directory
|
||||
"""
|
||||
sub_dirs = ["backtest_results", "data", "hyperopts", "hyperopt_results", "plot", "strategies", ]
|
||||
sub_dirs = ["backtest_results", "data", "hyperopts", "hyperopt_results", "notebooks",
|
||||
"plot", "strategies", ]
|
||||
folder = Path(directory)
|
||||
if not folder.is_dir():
|
||||
if create_dir:
|
||||
@@ -48,3 +51,26 @@ def create_userdata_dir(directory: str, create_dir=False) -> Path:
|
||||
if not subfolder.is_dir():
|
||||
subfolder.mkdir(parents=False)
|
||||
return folder
|
||||
|
||||
|
||||
def copy_sample_files(directory: Path, overwrite: bool = False) -> None:
|
||||
"""
|
||||
Copy files from templates to User data directory.
|
||||
:param directory: Directory to copy data to
|
||||
:param overwrite: Overwrite existing sample files
|
||||
"""
|
||||
if not directory.is_dir():
|
||||
raise OperationalException(f"Directory `{directory}` does not exist.")
|
||||
sourcedir = Path(__file__).parents[1] / "templates"
|
||||
for source, target in USER_DATA_FILES.items():
|
||||
targetdir = directory / target
|
||||
if not targetdir.is_dir():
|
||||
raise OperationalException(f"Directory `{targetdir}` does not exist.")
|
||||
targetfile = targetdir / source
|
||||
if targetfile.exists():
|
||||
if not overwrite:
|
||||
logger.warning(f"File `{targetfile}` exists already, not deploying sample file.")
|
||||
continue
|
||||
else:
|
||||
logger.warning(f"File `{targetfile}` exists already, overwriting.")
|
||||
shutil.copy(str(sourcedir / source), str(targetfile))
|
||||
|
@@ -1,11 +1,14 @@
|
||||
"""
|
||||
This module contains the argument manager class
|
||||
"""
|
||||
import logging
|
||||
import re
|
||||
from typing import Optional
|
||||
|
||||
import arrow
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TimeRange:
|
||||
"""
|
||||
@@ -27,6 +30,34 @@ class TimeRange:
|
||||
return (self.starttype == other.starttype and self.stoptype == other.stoptype
|
||||
and self.startts == other.startts and self.stopts == other.stopts)
|
||||
|
||||
def subtract_start(self, seconds) -> None:
|
||||
"""
|
||||
Subtracts <seconds> from startts if startts is set.
|
||||
:param seconds: Seconds to subtract from starttime
|
||||
:return: None (Modifies the object in place)
|
||||
"""
|
||||
if self.startts:
|
||||
self.startts = self.startts - seconds
|
||||
|
||||
def adjust_start_if_necessary(self, timeframe_secs: int, startup_candles: int,
|
||||
min_date: arrow.Arrow) -> None:
|
||||
"""
|
||||
Adjust startts by <startup_candles> candles.
|
||||
Applies only if no startup-candles have been available.
|
||||
:param timeframe_secs: Ticker timeframe in seconds e.g. `timeframe_to_seconds('5m')`
|
||||
:param startup_candles: Number of candles to move start-date forward
|
||||
:param min_date: Minimum data date loaded. Key kriterium to decide if start-time
|
||||
has to be moved
|
||||
:return: None (Modifies the object in place)
|
||||
"""
|
||||
if (not self.starttype or (startup_candles
|
||||
and min_date.timestamp >= self.startts)):
|
||||
# If no startts was defined, or backtest-data starts at the defined backtest-date
|
||||
logger.warning("Moving start-date by %s candles to account for startup time.",
|
||||
startup_candles)
|
||||
self.startts = (min_date.timestamp + timeframe_secs * startup_candles)
|
||||
self.starttype = 'date'
|
||||
|
||||
@staticmethod
|
||||
def parse_timerange(text: Optional[str]):
|
||||
"""
|
||||
|
Reference in New Issue
Block a user