Use Alias to type config objects

This commit is contained in:
Matthias 2022-09-18 13:20:36 +02:00
parent 9f23588154
commit 667853c504
34 changed files with 102 additions and 91 deletions

View File

@ -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'

View File

@ -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:

View File

@ -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',

View File

@ -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:

View File

@ -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.")

View File

@ -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]

View File

@ -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,

View File

@ -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

View File

@ -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

View File

@ -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)

View File

@ -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", {})

View File

@ -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 = "",
):

View File

@ -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.")

View File

@ -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.

View File

@ -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()

View File

@ -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
"""

View File

@ -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

View File

@ -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

View File

@ -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')

View File

@ -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

View File

@ -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
"""

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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

View File

@ -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()

View File

@ -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.
"""

View File

@ -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

View File

@ -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.'