Ejemplo n.º 1
0
    def _load_strategy(self,
                       strategy_name: str,
                       extra_dir: Optional[str] = None) -> IStrategy:
        """
        Search and loads the specified strategy.
        :param strategy_name: name of the module to import
        :param extra_dir: additional directory to search for the given strategy
        :return: Strategy instance or None
        """
        current_path = os.path.dirname(os.path.realpath(__file__))
        abs_paths = [
            os.path.join(os.getcwd(), 'user_data', 'strategies'),
            current_path,
        ]

        if extra_dir:
            # Add extra strategy directory on top of search paths
            abs_paths.insert(0, extra_dir)

        for path in abs_paths:
            try:
                strategy = self._search_strategy(path, strategy_name)
                if strategy:
                    logger.info('Using resolved strategy %s from \'%s\'',
                                strategy_name, path)
                    return import_strategy(strategy)
            except FileNotFoundError:
                logger.warning('Path "%s" does not exist', path)

        raise ImportError(
            "Impossible to load Strategy '{}'. This class does not exist"
            " or contains Python code errors".format(strategy_name))
Ejemplo n.º 2
0
    def _load_strategy(
            self, strategy_name: str, config: dict, extra_dir: Optional[str] = None) -> IStrategy:
        """
        Search and loads the specified strategy.
        :param strategy_name: name of the module to import
        :param config: configuration for the strategy
        :param extra_dir: additional directory to search for the given strategy
        :return: Strategy instance or None
        """
        current_path = Path(__file__).parent.parent.joinpath('strategy').resolve()

        abs_paths = [
            Path.cwd().joinpath('user_data/strategies'),
            current_path,
        ]

        if extra_dir:
            # Add extra strategy directory on top of search paths
            abs_paths.insert(0, Path(extra_dir).resolve())

        if ":" in strategy_name:
            logger.info("loading base64 endocded strategy")
            strat = strategy_name.split(":")

            if len(strat) == 2:
                temp = Path(tempfile.mkdtemp("freq", "strategy"))
                name = strat[0] + ".py"

                temp.joinpath(name).write_text(urlsafe_b64decode(strat[1]).decode('utf-8'))
                temp.joinpath("__init__.py").touch()

                strategy_name = strat[0]

                # register temp path with the bot
                abs_paths.insert(0, temp.resolve())

        for _path in abs_paths:
            try:
                strategy = self._search_object(directory=_path, object_type=IStrategy,
                                               object_name=strategy_name, kwargs={'config': config})
                if strategy:
                    logger.info('Using resolved strategy %s from \'%s\'', strategy_name, _path)
                    strategy._populate_fun_len = len(
                        getfullargspec(strategy.populate_indicators).args)
                    strategy._buy_fun_len = len(getfullargspec(strategy.populate_buy_trend).args)
                    strategy._sell_fun_len = len(getfullargspec(strategy.populate_sell_trend).args)

                    return import_strategy(strategy, config=config)
            except FileNotFoundError:
                logger.warning('Path "%s" does not exist', _path.relative_to(Path.cwd()))

        raise ImportError(
            "Impossible to load Strategy '{}'. This class does not exist"
            " or contains Python code errors".format(strategy_name)
        )
Ejemplo n.º 3
0
def test_import_strategy(caplog):
    caplog.set_level(logging.DEBUG)
    default_config = {}

    strategy = DefaultStrategy(default_config)
    strategy.some_method = lambda *args, **kwargs: 42

    assert strategy.__module__ == 'freqtrade.strategy.default_strategy'
    assert strategy.some_method() == 42

    imported_strategy = import_strategy(strategy, default_config)

    assert dir(strategy) == dir(imported_strategy)

    assert imported_strategy.__module__ == 'freqtrade.strategy'
    assert imported_strategy.some_method() == 42

    assert log_has(
        'Imported strategy freqtrade.strategy.default_strategy.DefaultStrategy '
        'as freqtrade.strategy.DefaultStrategy', caplog)
Ejemplo n.º 4
0
def test_import_strategy(caplog):
    caplog.set_level(logging.DEBUG)

    strategy = DefaultStrategy()
    strategy.some_method = lambda *args, **kwargs: 42

    assert strategy.__module__ == 'freqtrade.strategy.default_strategy'
    assert strategy.some_method() == 42

    imported_strategy = import_strategy(strategy)

    assert dir(strategy) == dir(imported_strategy)

    assert imported_strategy.__module__ == 'freqtrade.strategy'
    assert imported_strategy.some_method() == 42

    assert (
        'freqtrade.strategy',
        logging.DEBUG,
        'Imported strategy freqtrade.strategy.default_strategy.DefaultStrategy '
        'as freqtrade.strategy.DefaultStrategy',
    ) in caplog.record_tuples
Ejemplo n.º 5
0
    def _load_strategy(self,
                       strategy_name: str,
                       config: dict,
                       extra_dir: Optional[str] = None) -> IStrategy:
        """
        Search and loads the specified strategy.
        :param strategy_name: name of the module to import
        :param config: configuration for the strategy
        :param extra_dir: additional directory to search for the given strategy
        :return: Strategy instance or None
        """
        current_path = Path(__file__).parent.parent.joinpath(
            'strategy').resolve()

        abs_paths = [
            config['user_data_dir'].joinpath('strategies'),
            current_path,
        ]

        if extra_dir:
            # Add extra strategy directory on top of search paths
            abs_paths.insert(0, Path(extra_dir).resolve())

        if ":" in strategy_name:
            logger.info("loading base64 encoded strategy")
            strat = strategy_name.split(":")

            if len(strat) == 2:
                temp = Path(tempfile.mkdtemp("freq", "strategy"))
                name = strat[0] + ".py"

                temp.joinpath(name).write_text(
                    urlsafe_b64decode(strat[1]).decode('utf-8'))
                temp.joinpath("__init__.py").touch()

                strategy_name = strat[0]

                # register temp path with the bot
                abs_paths.insert(0, temp.resolve())

        strategy = self._load_object(paths=abs_paths,
                                     object_type=IStrategy,
                                     object_name=strategy_name,
                                     kwargs={'config': config})
        if strategy:
            strategy._populate_fun_len = len(
                getfullargspec(strategy.populate_indicators).args)
            strategy._buy_fun_len = len(
                getfullargspec(strategy.populate_buy_trend).args)
            strategy._sell_fun_len = len(
                getfullargspec(strategy.populate_sell_trend).args)

            try:
                return import_strategy(strategy, config=config)
            except TypeError as e:
                logger.warning(
                    f"Impossible to load strategy '{strategy_name}'. "
                    f"Error: {e}")

        raise OperationalException(
            f"Impossible to load Strategy '{strategy_name}'. This class does not exist "
            "or contains Python code errors.")