From 667853c50444be2768b7e43d9ab58ec25540d0cc Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 18 Sep 2022 13:20:36 +0200 Subject: [PATCH] Use Alias to type config objects --- freqtrade/configuration/check_exchange.py | 4 +-- freqtrade/configuration/configuration.py | 31 ++++++++++--------- .../configuration/deprecated_settings.py | 11 ++++--- .../configuration/directory_operations.py | 6 ++-- freqtrade/configuration/load_config.py | 4 +-- freqtrade/constants.py | 4 ++- freqtrade/data/converter.py | 4 +-- freqtrade/data/dataprovider.py | 4 +-- freqtrade/edge/edge_positioning.py | 5 ++- freqtrade/exchange/exchange.py | 7 +++-- freqtrade/freqai/data_drawer.py | 3 +- freqtrade/freqai/data_kitchen.py | 3 +- freqtrade/freqai/freqai_interface.py | 6 ++-- freqtrade/freqai/utils.py | 9 +++--- freqtrade/freqtradebot.py | 4 +-- freqtrade/loggers.py | 4 +-- freqtrade/optimize/backtesting.py | 4 +-- freqtrade/optimize/edge_cli.py | 4 +-- freqtrade/optimize/hyperopt.py | 6 ++-- freqtrade/optimize/hyperopt_interface.py | 3 +- freqtrade/optimize/hyperopt_tools.py | 4 +-- freqtrade/plugins/pairlist/SpreadFilter.py | 3 +- freqtrade/plugins/pairlist/StaticPairList.py | 3 +- .../plugins/pairlist/VolatilityFilter.py | 4 +-- freqtrade/plugins/pairlist/VolumePairList.py | 4 +-- freqtrade/plugins/protections/iprotection.py | 4 +-- .../plugins/protections/low_profit_pairs.py | 4 +-- .../protections/max_drawdown_protection.py | 4 +-- .../plugins/protections/stoploss_guard.py | 4 +-- freqtrade/rpc/api_server/webserver.py | 7 +++-- freqtrade/rpc/rpc.py | 8 ++--- freqtrade/strategy/hyper.py | 3 +- freqtrade/wallets.py | 4 +-- freqtrade/worker.py | 11 ++++--- 34 files changed, 102 insertions(+), 91 deletions(-) diff --git a/freqtrade/configuration/check_exchange.py b/freqtrade/configuration/check_exchange.py index 2be13ce4f..c3d859275 100644 --- a/freqtrade/configuration/check_exchange.py +++ b/freqtrade/configuration/check_exchange.py @@ -1,6 +1,6 @@ import logging -from typing import Any, Dict +from freqtrade.constants import Config from freqtrade.enums import RunMode from freqtrade.exceptions import OperationalException from freqtrade.exchange import (available_exchanges, is_exchange_known_ccxt, @@ -10,7 +10,7 @@ from freqtrade.exchange import (available_exchanges, is_exchange_known_ccxt, logger = logging.getLogger(__name__) -def check_exchange(config: Dict[str, Any], check_for_bad: bool = True) -> bool: +def check_exchange(config: Config, check_for_bad: bool = True) -> bool: """ Check if the exchange name in the config file is supported by Freqtrade :param check_for_bad: if True, check the exchange against the list of known 'bad' diff --git a/freqtrade/configuration/configuration.py b/freqtrade/configuration/configuration.py index 7c68ac46c..76105cc4d 100644 --- a/freqtrade/configuration/configuration.py +++ b/freqtrade/configuration/configuration.py @@ -13,6 +13,7 @@ from freqtrade.configuration.deprecated_settings import process_temporary_deprec from freqtrade.configuration.directory_operations import create_datadir, create_userdata_dir from freqtrade.configuration.environment_vars import enironment_vars_to_dict from freqtrade.configuration.load_config import load_file, load_from_files +from freqtrade.constants import Config from freqtrade.enums import NON_UTIL_MODES, TRADING_MODES, CandleType, RunMode, TradingMode from freqtrade.exceptions import OperationalException from freqtrade.loggers import setup_logging @@ -30,10 +31,10 @@ class Configuration: def __init__(self, args: Dict[str, Any], runmode: RunMode = None) -> None: self.args = args - self.config: Optional[Dict[str, Any]] = None + self.config: Optional[Config] = None self.runmode = runmode - def get_config(self) -> Dict[str, Any]: + def get_config(self) -> Config: """ Return the config. Use this method to get the bot config :return: Dict: Bot config @@ -65,7 +66,7 @@ class Configuration: :return: Configuration dictionary """ # Load all configs - config: Dict[str, Any] = load_from_files(self.args.get("config", [])) + config: Config = load_from_files(self.args.get("config", [])) # Load environment variables env_data = enironment_vars_to_dict() @@ -108,7 +109,7 @@ class Configuration: return config - def _process_logging_options(self, config: Dict[str, Any]) -> None: + def _process_logging_options(self, config: Config) -> None: """ Extract information for sys.argv and load logging configuration: the -v/--verbose, --logfile options @@ -121,7 +122,7 @@ class Configuration: setup_logging(config) - def _process_trading_options(self, config: Dict[str, Any]) -> None: + def _process_trading_options(self, config: Config) -> None: if config['runmode'] not in TRADING_MODES: return @@ -137,7 +138,7 @@ class Configuration: logger.info(f'Using DB: "{parse_db_uri_for_logging(config["db_url"])}"') - def _process_common_options(self, config: Dict[str, Any]) -> None: + def _process_common_options(self, config: Config) -> None: # Set strategy if not specified in config and or if it's non default if self.args.get('strategy') or not config.get('strategy'): @@ -161,7 +162,7 @@ class Configuration: if 'sd_notify' in self.args and self.args['sd_notify']: config['internals'].update({'sd_notify': True}) - def _process_datadir_options(self, config: Dict[str, Any]) -> None: + def _process_datadir_options(self, config: Config) -> None: """ Extract information for sys.argv and load directory configurations --user-data, --datadir @@ -195,7 +196,7 @@ class Configuration: config['exportfilename'] = (config['user_data_dir'] / 'backtest_results') - def _process_optimize_options(self, config: Dict[str, Any]) -> None: + def _process_optimize_options(self, config: Config) -> None: # This will override the strategy configuration self._args_to_config(config, argname='timeframe', @@ -380,7 +381,7 @@ class Configuration: self._args_to_config(config, argname="hyperopt_ignore_missing_space", logstring="Paramter --ignore-missing-space detected: {}") - def _process_plot_options(self, config: Dict[str, Any]) -> None: + def _process_plot_options(self, config: Config) -> None: self._args_to_config(config, argname='pairs', logstring='Using pairs {}') @@ -432,7 +433,7 @@ class Configuration: self._args_to_config(config, argname='show_timerange', logstring='Detected --show-timerange') - def _process_data_options(self, config: Dict[str, Any]) -> None: + def _process_data_options(self, config: Config) -> None: self._args_to_config(config, argname='new_pairs_days', logstring='Detected --new-pairs-days: {}') self._args_to_config(config, argname='trading_mode', @@ -443,7 +444,7 @@ class Configuration: self._args_to_config(config, argname='candle_types', logstring='Detected --candle-types: {}') - def _process_analyze_options(self, config: Dict[str, Any]) -> None: + def _process_analyze_options(self, config: Config) -> None: self._args_to_config(config, argname='analysis_groups', logstring='Analysis reason groups: {}') @@ -456,7 +457,7 @@ class Configuration: self._args_to_config(config, argname='indicator_list', logstring='Analysis indicator list: {}') - def _process_runmode(self, config: Dict[str, Any]) -> None: + def _process_runmode(self, config: Config) -> None: self._args_to_config(config, argname='dry_run', logstring='Parameter --dry-run detected, ' @@ -469,7 +470,7 @@ class Configuration: config.update({'runmode': self.runmode}) - def _process_freqai_options(self, config: Dict[str, Any]) -> None: + def _process_freqai_options(self, config: Config) -> None: self._args_to_config(config, argname='freqaimodel', logstring='Using freqaimodel class name: {}') @@ -479,7 +480,7 @@ class Configuration: return - def _args_to_config(self, config: Dict[str, Any], argname: str, + def _args_to_config(self, config: Config, argname: str, logstring: str, logfun: Optional[Callable] = None, deprecated_msg: Optional[str] = None) -> None: """ @@ -502,7 +503,7 @@ class Configuration: if deprecated_msg: warnings.warn(f"DEPRECATED: {deprecated_msg}", DeprecationWarning) - def _resolve_pairs_list(self, config: Dict[str, Any]) -> None: + def _resolve_pairs_list(self, config: Config) -> None: """ Helper for download script. Takes first found: diff --git a/freqtrade/configuration/deprecated_settings.py b/freqtrade/configuration/deprecated_settings.py index e88383785..46c19a5b2 100644 --- a/freqtrade/configuration/deprecated_settings.py +++ b/freqtrade/configuration/deprecated_settings.py @@ -3,15 +3,16 @@ Functions to handle deprecated settings """ import logging -from typing import Any, Dict, Optional +from typing import Optional +from freqtrade.constants import Config from freqtrade.exceptions import OperationalException logger = logging.getLogger(__name__) -def check_conflicting_settings(config: Dict[str, Any], +def check_conflicting_settings(config: Config, section_old: Optional[str], name_old: str, section_new: Optional[str], name_new: str) -> None: section_new_config = config.get(section_new, {}) if section_new else config @@ -28,7 +29,7 @@ def check_conflicting_settings(config: Dict[str, Any], ) -def process_removed_setting(config: Dict[str, Any], +def process_removed_setting(config: Config, section1: str, name1: str, section2: Optional[str], name2: str) -> None: """ @@ -47,7 +48,7 @@ def process_removed_setting(config: Dict[str, Any], ) -def process_deprecated_setting(config: Dict[str, Any], +def process_deprecated_setting(config: Config, section_old: Optional[str], name_old: str, section_new: Optional[str], name_new: str ) -> None: @@ -69,7 +70,7 @@ def process_deprecated_setting(config: Dict[str, Any], del section_old_config[name_old] -def process_temporary_deprecated_settings(config: Dict[str, Any]) -> None: +def process_temporary_deprecated_settings(config: Config) -> None: # Kept for future deprecated / moved settings # check_conflicting_settings(config, 'ask_strategy', 'use_sell_signal', diff --git a/freqtrade/configuration/directory_operations.py b/freqtrade/configuration/directory_operations.py index 771fd53cc..f70310ee1 100644 --- a/freqtrade/configuration/directory_operations.py +++ b/freqtrade/configuration/directory_operations.py @@ -1,16 +1,16 @@ import logging import shutil from pathlib import Path -from typing import Any, Dict, Optional +from typing import Optional -from freqtrade.constants import USER_DATA_FILES +from freqtrade.constants import USER_DATA_FILES, Config from freqtrade.exceptions import OperationalException logger = logging.getLogger(__name__) -def create_datadir(config: Dict[str, Any], datadir: Optional[str] = None) -> Path: +def create_datadir(config: Config, datadir: Optional[str] = None) -> Path: folder = Path(datadir) if datadir else Path(f"{config['user_data_dir']}/data") if not datadir: diff --git a/freqtrade/configuration/load_config.py b/freqtrade/configuration/load_config.py index 3fcbd1f2f..6d0321ba0 100644 --- a/freqtrade/configuration/load_config.py +++ b/freqtrade/configuration/load_config.py @@ -10,7 +10,7 @@ from typing import Any, Dict, List import rapidjson -from freqtrade.constants import MINIMAL_CONFIG +from freqtrade.constants import MINIMAL_CONFIG, Config from freqtrade.exceptions import OperationalException from freqtrade.misc import deep_merge_dicts @@ -80,7 +80,7 @@ def load_from_files(files: List[str], base_path: Path = None, level: int = 0) -> Recursively load configuration files if specified. Sub-files are assumed to be relative to the initial config. """ - config: Dict[str, Any] = {} + config: Config = {} if level > 5: raise OperationalException("Config loop detected.") diff --git a/freqtrade/constants.py b/freqtrade/constants.py index bab8c4816..077c4ecbf 100644 --- a/freqtrade/constants.py +++ b/freqtrade/constants.py @@ -3,7 +3,7 @@ """ bot constants """ -from typing import List, Literal, Tuple +from typing import Any, Dict, List, Literal, Tuple from freqtrade.enums import CandleType @@ -603,3 +603,5 @@ LongShort = Literal['long', 'short'] EntryExit = Literal['entry', 'exit'] BuySell = Literal['buy', 'sell'] MakerTaker = Literal['maker', 'taker'] + +Config = Dict[str, Any] diff --git a/freqtrade/data/converter.py b/freqtrade/data/converter.py index 84c57be41..bdd010af3 100644 --- a/freqtrade/data/converter.py +++ b/freqtrade/data/converter.py @@ -10,7 +10,7 @@ from typing import Any, Dict, List import pandas as pd from pandas import DataFrame, to_datetime -from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS, TradeList +from freqtrade.constants import DEFAULT_DATAFRAME_COLUMNS, DEFAULT_TRADES_COLUMNS, Config, TradeList from freqtrade.enums import CandleType @@ -263,7 +263,7 @@ def convert_trades_format(config: Dict[str, Any], convert_from: str, convert_to: def convert_ohlcv_format( - config: Dict[str, Any], + config: Config, convert_from: str, convert_to: str, erase: bool, diff --git a/freqtrade/data/dataprovider.py b/freqtrade/data/dataprovider.py index c6519d2b8..43850ddd9 100644 --- a/freqtrade/data/dataprovider.py +++ b/freqtrade/data/dataprovider.py @@ -12,7 +12,7 @@ from typing import Any, Dict, List, Optional, Tuple from pandas import DataFrame from freqtrade.configuration import TimeRange -from freqtrade.constants import ListPairsWithTimeframes, PairWithTimeframe +from freqtrade.constants import Config, ListPairsWithTimeframes, PairWithTimeframe from freqtrade.data.history import load_pair_history from freqtrade.enums import CandleType, RunMode from freqtrade.exceptions import ExchangeError, OperationalException @@ -28,7 +28,7 @@ MAX_DATAFRAME_CANDLES = 1000 class DataProvider: - def __init__(self, config: dict, exchange: Optional[Exchange], pairlists=None) -> None: + def __init__(self, config: Config, exchange: Optional[Exchange], pairlists=None) -> None: self._config = config self._exchange = exchange self._pairlists = pairlists diff --git a/freqtrade/edge/edge_positioning.py b/freqtrade/edge/edge_positioning.py index af20e1645..45b4cd8f1 100644 --- a/freqtrade/edge/edge_positioning.py +++ b/freqtrade/edge/edge_positioning.py @@ -11,7 +11,7 @@ import utils_find_1st as utf1st from pandas import DataFrame from freqtrade.configuration import TimeRange -from freqtrade.constants import DATETIME_PRINT_FORMAT, UNLIMITED_STAKE_AMOUNT +from freqtrade.constants import DATETIME_PRINT_FORMAT, UNLIMITED_STAKE_AMOUNT, Config from freqtrade.data.history import get_timerange, load_data, refresh_data from freqtrade.enums import CandleType, ExitType, RunMode from freqtrade.exceptions import OperationalException @@ -42,10 +42,9 @@ class Edge: Author: https://github.com/mishaker """ - config: Dict = {} _cached_pairs: Dict[str, Any] = {} # Keeps a list of pairs - def __init__(self, config: Dict[str, Any], exchange, strategy) -> None: + def __init__(self, config: Config, exchange, strategy) -> None: self.config = config self.exchange = exchange diff --git a/freqtrade/exchange/exchange.py b/freqtrade/exchange/exchange.py index a2ddc16e8..c68fc5873 100644 --- a/freqtrade/exchange/exchange.py +++ b/freqtrade/exchange/exchange.py @@ -21,7 +21,8 @@ from dateutil import parser from pandas import DataFrame from freqtrade.constants import (DEFAULT_AMOUNT_RESERVE_PERCENT, NON_OPEN_EXCHANGE_STATES, BuySell, - EntryExit, ListPairsWithTimeframes, MakerTaker, PairWithTimeframe) + Config, EntryExit, ListPairsWithTimeframes, MakerTaker, + PairWithTimeframe) from freqtrade.data.converter import ohlcv_to_dataframe, trades_dict_to_list from freqtrade.enums import OPTIMIZE_MODES, CandleType, MarginMode, TradingMode from freqtrade.exceptions import (DDosProtection, ExchangeError, InsufficientFundsError, @@ -91,7 +92,7 @@ class Exchange: # TradingMode.SPOT always supported and not required in this list ] - def __init__(self, config: Dict[str, Any], validate: bool = True, + def __init__(self, config: Config, validate: bool = True, load_leverage_tiers: bool = False) -> None: """ Initializes this module with the given config, @@ -108,7 +109,7 @@ class Exchange: self._loop_lock = Lock() self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) - self._config: Dict = {} + self._config: Config = {} self._config.update(config) diff --git a/freqtrade/freqai/data_drawer.py b/freqtrade/freqai/data_drawer.py index 1c091f1be..a9fe8bdc9 100644 --- a/freqtrade/freqai/data_drawer.py +++ b/freqtrade/freqai/data_drawer.py @@ -16,6 +16,7 @@ from numpy.typing import NDArray from pandas import DataFrame from freqtrade.configuration import TimeRange +from freqtrade.constants import Config from freqtrade.data.history import load_pair_history from freqtrade.exceptions import OperationalException from freqtrade.freqai.data_kitchen import FreqaiDataKitchen @@ -58,7 +59,7 @@ class FreqaiDataDrawer: Juha Nykänen @suikula, Wagner Costa @wagnercosta, Johan Vlugt @Jooopieeert """ - def __init__(self, full_path: Path, config: dict, follow_mode: bool = False): + def __init__(self, full_path: Path, config: Config, follow_mode: bool = False): self.config = config self.freqai_info = config.get("freqai", {}) diff --git a/freqtrade/freqai/data_kitchen.py b/freqtrade/freqai/data_kitchen.py index e96a945eb..d2abd0ad2 100644 --- a/freqtrade/freqai/data_kitchen.py +++ b/freqtrade/freqai/data_kitchen.py @@ -18,6 +18,7 @@ from sklearn.model_selection import train_test_split from sklearn.neighbors import NearestNeighbors from freqtrade.configuration import TimeRange +from freqtrade.constants import Config from freqtrade.exceptions import OperationalException from freqtrade.exchange import timeframe_to_seconds from freqtrade.strategy.interface import IStrategy @@ -57,7 +58,7 @@ class FreqaiDataKitchen: def __init__( self, - config: Dict[str, Any], + config: Config, live: bool = False, pair: str = "", ): diff --git a/freqtrade/freqai/freqai_interface.py b/freqtrade/freqai/freqai_interface.py index 78931bed4..9a2c64cc3 100644 --- a/freqtrade/freqai/freqai_interface.py +++ b/freqtrade/freqai/freqai_interface.py @@ -14,7 +14,7 @@ from numpy.typing import NDArray from pandas import DataFrame from freqtrade.configuration import TimeRange -from freqtrade.constants import DATETIME_PRINT_FORMAT +from freqtrade.constants import DATETIME_PRINT_FORMAT, Config from freqtrade.enums import RunMode from freqtrade.exceptions import OperationalException from freqtrade.exchange import timeframe_to_seconds @@ -50,7 +50,7 @@ class IFreqaiModel(ABC): Juha Nykänen @suikula, Wagner Costa @wagnercosta, Johan Vlugt @Jooopieeert """ - def __init__(self, config: Dict[str, Any]) -> None: + def __init__(self, config: Config) -> None: self.config = config self.assert_config(self.config) @@ -99,7 +99,7 @@ class IFreqaiModel(ABC): """ return ({}) - def assert_config(self, config: Dict[str, Any]) -> None: + def assert_config(self, config: Config) -> None: if not config.get("freqai", {}): raise OperationalException("No freqai parameters found in configuration file.") diff --git a/freqtrade/freqai/utils.py b/freqtrade/freqai/utils.py index 6a70f050f..063965ded 100644 --- a/freqtrade/freqai/utils.py +++ b/freqtrade/freqai/utils.py @@ -2,6 +2,7 @@ import logging from datetime import datetime, timezone from freqtrade.configuration import TimeRange +from freqtrade.constants import Config from freqtrade.data.dataprovider import DataProvider from freqtrade.data.history.history_utils import refresh_backtest_ohlcv_data from freqtrade.exceptions import OperationalException @@ -13,7 +14,7 @@ from freqtrade.plugins.pairlist.pairlist_helpers import dynamic_expand_pairlist logger = logging.getLogger(__name__) -def download_all_data_for_training(dp: DataProvider, config: dict) -> None: +def download_all_data_for_training(dp: DataProvider, config: Config) -> None: """ Called only once upon start of bot to download the necessary data for populating indicators and training the model. @@ -47,9 +48,7 @@ def download_all_data_for_training(dp: DataProvider, config: dict) -> None: ) -def get_required_data_timerange( - config: dict -) -> TimeRange: +def get_required_data_timerange(config: Config) -> TimeRange: """ Used to compute the required data download time range for auto data-download in FreqAI @@ -86,7 +85,7 @@ def get_required_data_timerange( # Keep below for when we wish to download heterogeneously lengthed data for FreqAI. -# def download_all_data_for_training(dp: DataProvider, config: dict) -> None: +# def download_all_data_for_training(dp: DataProvider, config: Config) -> None: # """ # Called only once upon start of bot to download the necessary data for # populating indicators and training a FreqAI model. diff --git a/freqtrade/freqtradebot.py b/freqtrade/freqtradebot.py index 3eaec5c98..83abc9bc5 100644 --- a/freqtrade/freqtradebot.py +++ b/freqtrade/freqtradebot.py @@ -13,7 +13,7 @@ from schedule import Scheduler from freqtrade import __version__, constants from freqtrade.configuration import validate_config_consistency -from freqtrade.constants import BuySell, LongShort +from freqtrade.constants import BuySell, Config, LongShort from freqtrade.data.converter import order_book_to_dataframe from freqtrade.data.dataprovider import DataProvider from freqtrade.edge import Edge @@ -44,7 +44,7 @@ class FreqtradeBot(LoggingMixin): This is from here the bot start its logic. """ - def __init__(self, config: Dict[str, Any]) -> None: + def __init__(self, config: Config) -> None: """ Init all variables and objects the bot needs to work :param config: configuration dict, you can use Configuration.get_config() diff --git a/freqtrade/loggers.py b/freqtrade/loggers.py index e5b6ddbe9..f365053c9 100644 --- a/freqtrade/loggers.py +++ b/freqtrade/loggers.py @@ -2,8 +2,8 @@ import logging import sys from logging import Formatter from logging.handlers import BufferingHandler, RotatingFileHandler, SysLogHandler -from typing import Any, Dict +from freqtrade.constants import Config from freqtrade.exceptions import OperationalException @@ -73,7 +73,7 @@ def setup_logging_pre() -> None: ) -def setup_logging(config: Dict[str, Any]) -> None: +def setup_logging(config: Config) -> None: """ Process -v/--verbose, --logfile options """ diff --git a/freqtrade/optimize/backtesting.py b/freqtrade/optimize/backtesting.py index 105851e60..0a05d740d 100644 --- a/freqtrade/optimize/backtesting.py +++ b/freqtrade/optimize/backtesting.py @@ -15,7 +15,7 @@ from pandas import DataFrame from freqtrade import constants from freqtrade.configuration import TimeRange, validate_config_consistency -from freqtrade.constants import DATETIME_PRINT_FORMAT, LongShort +from freqtrade.constants import DATETIME_PRINT_FORMAT, Config, LongShort from freqtrade.data import history from freqtrade.data.btanalysis import find_existing_backtest_stats, trade_list_to_dataframe from freqtrade.data.converter import trim_dataframe, trim_dataframes @@ -70,7 +70,7 @@ class Backtesting: backtesting.start() """ - def __init__(self, config: Dict[str, Any]) -> None: + def __init__(self, config: Config) -> None: LoggingMixin.show_output = False self.config = config diff --git a/freqtrade/optimize/edge_cli.py b/freqtrade/optimize/edge_cli.py index aa3b02529..2eb1c53f5 100644 --- a/freqtrade/optimize/edge_cli.py +++ b/freqtrade/optimize/edge_cli.py @@ -4,10 +4,10 @@ This module contains the edge backtesting interface """ import logging -from typing import Any, Dict from freqtrade import constants from freqtrade.configuration import TimeRange, validate_config_consistency +from freqtrade.constants import Config from freqtrade.data.dataprovider import DataProvider from freqtrade.edge import Edge from freqtrade.optimize.optimize_reports import generate_edge_table @@ -26,7 +26,7 @@ class EdgeCli: edge.start() """ - def __init__(self, config: Dict[str, Any]) -> None: + def __init__(self, config: Config) -> None: self.config = config # Ensure using dry-run diff --git a/freqtrade/optimize/hyperopt.py b/freqtrade/optimize/hyperopt.py index f15e0b7d8..aef8405d5 100644 --- a/freqtrade/optimize/hyperopt.py +++ b/freqtrade/optimize/hyperopt.py @@ -21,7 +21,7 @@ from joblib import Parallel, cpu_count, delayed, dump, load, wrap_non_picklable_ from joblib.externals import cloudpickle from pandas import DataFrame -from freqtrade.constants import DATETIME_PRINT_FORMAT, FTHYPT_FILEVERSION, LAST_BT_RESULT_FN +from freqtrade.constants import DATETIME_PRINT_FORMAT, FTHYPT_FILEVERSION, LAST_BT_RESULT_FN, Config from freqtrade.data.converter import trim_dataframes from freqtrade.data.history import get_timerange from freqtrade.enums import HyperoptState @@ -66,7 +66,7 @@ class Hyperopt: hyperopt.start() """ - def __init__(self, config: Dict[str, Any]) -> None: + def __init__(self, config: Config) -> None: self.buy_space: List[Dimension] = [] self.sell_space: List[Dimension] = [] self.protection_space: List[Dimension] = [] @@ -132,7 +132,7 @@ class Hyperopt: self.print_json = self.config.get('print_json', False) @staticmethod - def get_lock_filename(config: Dict[str, Any]) -> str: + def get_lock_filename(config: Config) -> str: return str(config['user_data_dir'] / 'hyperopt.lock') diff --git a/freqtrade/optimize/hyperopt_interface.py b/freqtrade/optimize/hyperopt_interface.py index b1c68caca..a7c64ffb0 100644 --- a/freqtrade/optimize/hyperopt_interface.py +++ b/freqtrade/optimize/hyperopt_interface.py @@ -10,6 +10,7 @@ from typing import Dict, List, Union from sklearn.base import RegressorMixin from skopt.space import Categorical, Dimension, Integer +from freqtrade.constants import Config from freqtrade.exchange import timeframe_to_minutes from freqtrade.misc import round_dict from freqtrade.optimize.space import SKDecimal @@ -32,7 +33,7 @@ class IHyperOpt(ABC): timeframe: str strategy: IStrategy - def __init__(self, config: dict) -> None: + def __init__(self, config: Config) -> None: self.config = config # Assign timeframe to be used in hyperopt diff --git a/freqtrade/optimize/hyperopt_tools.py b/freqtrade/optimize/hyperopt_tools.py index 9b022d519..d1f776e3d 100755 --- a/freqtrade/optimize/hyperopt_tools.py +++ b/freqtrade/optimize/hyperopt_tools.py @@ -12,7 +12,7 @@ import tabulate from colorama import Fore, Style from pandas import isna, json_normalize -from freqtrade.constants import FTHYPT_FILEVERSION, USERPATH_STRATEGIES +from freqtrade.constants import FTHYPT_FILEVERSION, USERPATH_STRATEGIES, Config from freqtrade.enums import HyperoptState from freqtrade.exceptions import OperationalException from freqtrade.misc import deep_merge_dicts, round_coin_value, round_dict, safe_value_fallback2 @@ -45,7 +45,7 @@ class HyperoptStateContainer(): class HyperoptTools(): @staticmethod - def get_strategy_filename(config: Dict, strategy_name: str) -> Optional[Path]: + def get_strategy_filename(config: Config, strategy_name: str) -> Optional[Path]: """ Get Strategy-location (filename) from strategy_name """ diff --git a/freqtrade/plugins/pairlist/SpreadFilter.py b/freqtrade/plugins/pairlist/SpreadFilter.py index 43856b451..1f20af305 100644 --- a/freqtrade/plugins/pairlist/SpreadFilter.py +++ b/freqtrade/plugins/pairlist/SpreadFilter.py @@ -4,6 +4,7 @@ Spread pair list filter import logging from typing import Any, Dict +from freqtrade.constants import Config from freqtrade.exceptions import OperationalException from freqtrade.plugins.pairlist.IPairList import IPairList @@ -14,7 +15,7 @@ logger = logging.getLogger(__name__) class SpreadFilter(IPairList): def __init__(self, exchange, pairlistmanager, - config: Dict[str, Any], pairlistconfig: Dict[str, Any], + config: Config, pairlistconfig: Dict[str, Any], pairlist_pos: int) -> None: super().__init__(exchange, pairlistmanager, config, pairlistconfig, pairlist_pos) diff --git a/freqtrade/plugins/pairlist/StaticPairList.py b/freqtrade/plugins/pairlist/StaticPairList.py index 30fa474e4..83a0fa0c8 100644 --- a/freqtrade/plugins/pairlist/StaticPairList.py +++ b/freqtrade/plugins/pairlist/StaticPairList.py @@ -7,6 +7,7 @@ import logging from copy import deepcopy from typing import Any, Dict, List +from freqtrade.constants import Config from freqtrade.plugins.pairlist.IPairList import IPairList @@ -16,7 +17,7 @@ logger = logging.getLogger(__name__) class StaticPairList(IPairList): def __init__(self, exchange, pairlistmanager, - config: Dict[str, Any], pairlistconfig: Dict[str, Any], + config: Config, pairlistconfig: Dict[str, Any], pairlist_pos: int) -> None: super().__init__(exchange, pairlistmanager, config, pairlistconfig, pairlist_pos) diff --git a/freqtrade/plugins/pairlist/VolatilityFilter.py b/freqtrade/plugins/pairlist/VolatilityFilter.py index bab44bdd1..c9af3a7b3 100644 --- a/freqtrade/plugins/pairlist/VolatilityFilter.py +++ b/freqtrade/plugins/pairlist/VolatilityFilter.py @@ -11,7 +11,7 @@ import numpy as np from cachetools import TTLCache from pandas import DataFrame -from freqtrade.constants import ListPairsWithTimeframes +from freqtrade.constants import Config, ListPairsWithTimeframes from freqtrade.exceptions import OperationalException from freqtrade.misc import plural from freqtrade.plugins.pairlist.IPairList import IPairList @@ -26,7 +26,7 @@ class VolatilityFilter(IPairList): """ def __init__(self, exchange, pairlistmanager, - config: Dict[str, Any], pairlistconfig: Dict[str, Any], + config: Config, pairlistconfig: Dict[str, Any], pairlist_pos: int) -> None: super().__init__(exchange, pairlistmanager, config, pairlistconfig, pairlist_pos) diff --git a/freqtrade/plugins/pairlist/VolumePairList.py b/freqtrade/plugins/pairlist/VolumePairList.py index d7cc6e5ec..9dcada291 100644 --- a/freqtrade/plugins/pairlist/VolumePairList.py +++ b/freqtrade/plugins/pairlist/VolumePairList.py @@ -9,7 +9,7 @@ from typing import Any, Dict, List from cachetools import TTLCache -from freqtrade.constants import ListPairsWithTimeframes +from freqtrade.constants import Config, ListPairsWithTimeframes from freqtrade.exceptions import OperationalException from freqtrade.exchange import timeframe_to_minutes, timeframe_to_prev_date from freqtrade.misc import format_ms_time @@ -25,7 +25,7 @@ SORT_VALUES = ['quoteVolume'] class VolumePairList(IPairList): def __init__(self, exchange, pairlistmanager, - config: Dict[str, Any], pairlistconfig: Dict[str, Any], + config: Config, pairlistconfig: Dict[str, Any], pairlist_pos: int) -> None: super().__init__(exchange, pairlistmanager, config, pairlistconfig, pairlist_pos) diff --git a/freqtrade/plugins/protections/iprotection.py b/freqtrade/plugins/protections/iprotection.py index 890988226..8e1589217 100644 --- a/freqtrade/plugins/protections/iprotection.py +++ b/freqtrade/plugins/protections/iprotection.py @@ -5,7 +5,7 @@ from dataclasses import dataclass from datetime import datetime, timedelta, timezone from typing import Any, Dict, List, Optional -from freqtrade.constants import LongShort +from freqtrade.constants import Config, LongShort from freqtrade.exchange import timeframe_to_minutes from freqtrade.misc import plural from freqtrade.mixins import LoggingMixin @@ -30,7 +30,7 @@ class IProtection(LoggingMixin, ABC): # Can stop trading for one pair has_local_stop: bool = False - def __init__(self, config: Dict[str, Any], protection_config: Dict[str, Any]) -> None: + def __init__(self, config: Config, protection_config: Dict[str, Any]) -> None: self._config = config self._protection_config = protection_config self._stop_duration_candles: Optional[int] = None diff --git a/freqtrade/plugins/protections/low_profit_pairs.py b/freqtrade/plugins/protections/low_profit_pairs.py index 099242b8d..f638673fa 100644 --- a/freqtrade/plugins/protections/low_profit_pairs.py +++ b/freqtrade/plugins/protections/low_profit_pairs.py @@ -3,7 +3,7 @@ import logging from datetime import datetime, timedelta from typing import Any, Dict, Optional -from freqtrade.constants import LongShort +from freqtrade.constants import Config, LongShort from freqtrade.persistence import Trade from freqtrade.plugins.protections import IProtection, ProtectionReturn @@ -16,7 +16,7 @@ class LowProfitPairs(IProtection): has_global_stop: bool = False has_local_stop: bool = True - def __init__(self, config: Dict[str, Any], protection_config: Dict[str, Any]) -> None: + def __init__(self, config: Config, protection_config: Dict[str, Any]) -> None: super().__init__(config, protection_config) self._trade_limit = protection_config.get('trade_limit', 1) diff --git a/freqtrade/plugins/protections/max_drawdown_protection.py b/freqtrade/plugins/protections/max_drawdown_protection.py index e0b016cb8..8193dc7e4 100644 --- a/freqtrade/plugins/protections/max_drawdown_protection.py +++ b/freqtrade/plugins/protections/max_drawdown_protection.py @@ -5,7 +5,7 @@ from typing import Any, Dict, Optional import pandas as pd -from freqtrade.constants import LongShort +from freqtrade.constants import Config, LongShort from freqtrade.data.metrics import calculate_max_drawdown from freqtrade.persistence import Trade from freqtrade.plugins.protections import IProtection, ProtectionReturn @@ -19,7 +19,7 @@ class MaxDrawdown(IProtection): has_global_stop: bool = True has_local_stop: bool = False - def __init__(self, config: Dict[str, Any], protection_config: Dict[str, Any]) -> None: + def __init__(self, config: Config, protection_config: Dict[str, Any]) -> None: super().__init__(config, protection_config) self._trade_limit = protection_config.get('trade_limit', 1) diff --git a/freqtrade/plugins/protections/stoploss_guard.py b/freqtrade/plugins/protections/stoploss_guard.py index e80d13e9d..23ceebbc9 100644 --- a/freqtrade/plugins/protections/stoploss_guard.py +++ b/freqtrade/plugins/protections/stoploss_guard.py @@ -3,7 +3,7 @@ import logging from datetime import datetime, timedelta from typing import Any, Dict, Optional -from freqtrade.constants import LongShort +from freqtrade.constants import Config, LongShort from freqtrade.enums import ExitType from freqtrade.persistence import Trade from freqtrade.plugins.protections import IProtection, ProtectionReturn @@ -17,7 +17,7 @@ class StoplossGuard(IProtection): has_global_stop: bool = True has_local_stop: bool = True - def __init__(self, config: Dict[str, Any], protection_config: Dict[str, Any]) -> None: + def __init__(self, config: Config, protection_config: Dict[str, Any]) -> None: super().__init__(config, protection_config) self._trade_limit = protection_config.get('trade_limit', 10) diff --git a/freqtrade/rpc/api_server/webserver.py b/freqtrade/rpc/api_server/webserver.py index 0da129583..642f25e47 100644 --- a/freqtrade/rpc/api_server/webserver.py +++ b/freqtrade/rpc/api_server/webserver.py @@ -8,6 +8,7 @@ from fastapi import Depends, FastAPI from fastapi.middleware.cors import CORSMiddleware from starlette.responses import JSONResponse +from freqtrade.constants import Config from freqtrade.exceptions import OperationalException from freqtrade.rpc.api_server.uvicorn_threaded import UvicornServer from freqtrade.rpc.rpc import RPC, RPCException, RPCHandler @@ -37,10 +38,10 @@ class ApiServer(RPCHandler): _bt = None _bt_data = None _bt_timerange = None - _bt_last_config: Dict[str, Any] = {} + _bt_last_config: Config = {} _has_rpc: bool = False _bgtask_running: bool = False - _config: Dict[str, Any] = {} + _config: Config = {} # Exchange - only available in webserver mode. _exchange = None @@ -54,7 +55,7 @@ class ApiServer(RPCHandler): ApiServer.__initialized = False return ApiServer.__instance - def __init__(self, config: Dict[str, Any], standalone: bool = False) -> None: + def __init__(self, config: Config, standalone: bool = False) -> None: ApiServer._config = config if self.__initialized and (standalone or self._standalone): return diff --git a/freqtrade/rpc/rpc.py b/freqtrade/rpc/rpc.py index 05599074c..6602cdd35 100644 --- a/freqtrade/rpc/rpc.py +++ b/freqtrade/rpc/rpc.py @@ -16,7 +16,7 @@ from pandas import DataFrame, NaT from freqtrade import __version__ from freqtrade.configuration.timerange import TimeRange -from freqtrade.constants import CANCEL_REASON, DATETIME_PRINT_FORMAT +from freqtrade.constants import CANCEL_REASON, DATETIME_PRINT_FORMAT, Config from freqtrade.data.history import load_data from freqtrade.data.metrics import calculate_max_drawdown from freqtrade.enums import (CandleType, ExitCheckTuple, ExitType, SignalDirection, State, @@ -58,7 +58,7 @@ class RPCException(Exception): class RPCHandler: - def __init__(self, rpc: 'RPC', config: Dict[str, Any]) -> None: + def __init__(self, rpc: 'RPC', config: Config) -> None: """ Initializes RPCHandlers :param rpc: instance of RPC Helper class @@ -66,7 +66,7 @@ class RPCHandler: :return: None """ self._rpc = rpc - self._config: Dict[str, Any] = config + self._config: Config = config @property def name(self) -> str: @@ -96,7 +96,7 @@ class RPC: :return: None """ self._freqtrade = freqtrade - self._config: Dict[str, Any] = freqtrade.config + self._config: Config = freqtrade.config if self._config.get('fiat_display_currency'): self._fiat_converter = CryptoToFiatConverter() diff --git a/freqtrade/strategy/hyper.py b/freqtrade/strategy/hyper.py index 47377f238..6f62c9d3d 100644 --- a/freqtrade/strategy/hyper.py +++ b/freqtrade/strategy/hyper.py @@ -6,6 +6,7 @@ import logging from pathlib import Path from typing import Any, Dict, Iterator, List, Tuple, Type, Union +from freqtrade.constants import Config from freqtrade.exceptions import OperationalException from freqtrade.misc import deep_merge_dicts, json_load from freqtrade.optimize.hyperopt_tools import HyperoptTools @@ -21,7 +22,7 @@ class HyperStrategyMixin: strategy logic. """ - def __init__(self, config: Dict[str, Any], *args, **kwargs): + def __init__(self, config: Config, *args, **kwargs): """ Initialize hyperoptable strategy mixin. """ diff --git a/freqtrade/wallets.py b/freqtrade/wallets.py index 41115c72e..0a9ecc638 100644 --- a/freqtrade/wallets.py +++ b/freqtrade/wallets.py @@ -7,7 +7,7 @@ from typing import Dict, NamedTuple, Optional import arrow -from freqtrade.constants import UNLIMITED_STAKE_AMOUNT +from freqtrade.constants import UNLIMITED_STAKE_AMOUNT, Config from freqtrade.enums import RunMode, TradingMode from freqtrade.exceptions import DependencyException from freqtrade.exchange import Exchange @@ -35,7 +35,7 @@ class PositionWallet(NamedTuple): class Wallets: - def __init__(self, config: dict, exchange: Exchange, log: bool = True) -> None: + def __init__(self, config: Config, exchange: Exchange, log: bool = True) -> None: self._config = config self._log = log self._exchange = exchange diff --git a/freqtrade/worker.py b/freqtrade/worker.py index 66f718af0..dea0acc44 100755 --- a/freqtrade/worker.py +++ b/freqtrade/worker.py @@ -9,8 +9,9 @@ from typing import Any, Callable, Dict, Optional import sdnotify -from freqtrade import __version__, constants +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.exceptions import OperationalException, TemporaryError from freqtrade.freqtradebot import FreqtradeBot @@ -24,7 +25,7 @@ class Worker: Freqtradebot worker class """ - def __init__(self, args: Dict[str, Any], config: Dict[str, Any] = None) -> None: + def __init__(self, args: Dict[str, Any], config: Config = None) -> None: """ Init all variables and objects the bot needs to work """ @@ -53,7 +54,7 @@ class Worker: internals_config = self._config.get('internals', {}) self._throttle_secs = internals_config.get('process_throttle_secs', - constants.PROCESS_THROTTLE_SECS) + PROCESS_THROTTLE_SECS) self._heartbeat_interval = internals_config.get('heartbeat_interval', 60) self._sd_notify = sdnotify.SystemdNotifier() if \ @@ -151,8 +152,8 @@ class Worker: try: self.freqtrade.process() except TemporaryError as error: - logger.warning(f"Error: {error}, retrying in {constants.RETRY_TIMEOUT} seconds...") - time.sleep(constants.RETRY_TIMEOUT) + logger.warning(f"Error: {error}, retrying in {RETRY_TIMEOUT} seconds...") + time.sleep(RETRY_TIMEOUT) except OperationalException: tb = traceback.format_exc() hint = 'Issue `/start` if you think it is safe to restart.'