Use new TestStrategy (V3) by default in tests

This commit is contained in:
Matthias 2021-09-21 20:18:14 +02:00
parent 7a5c7e7020
commit c791b95405
21 changed files with 127 additions and 132 deletions

View File

@ -42,7 +42,7 @@ docker build --cache-from freqtrade:${TAG_ARM} --build-arg sourceimage=${CACHE_I
docker tag freqtrade:$TAG_PLOT_ARM ${CACHE_IMAGE}:$TAG_PLOT_ARM docker tag freqtrade:$TAG_PLOT_ARM ${CACHE_IMAGE}:$TAG_PLOT_ARM
# Run backtest # Run backtest
docker run --rm -v $(pwd)/config_examples/config_bittrex.example.json:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG_ARM} backtesting --datadir /tests/testdata --strategy-path /tests/strategy/strats/ --strategy StrategyTestV2 docker run --rm -v $(pwd)/config_examples/config_bittrex.example.json:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG_ARM} backtesting --datadir /tests/testdata --strategy-path /tests/strategy/strats/ --strategy StrategyTestV3
if [ $? -ne 0 ]; then if [ $? -ne 0 ]; then
echo "failed running backtest" echo "failed running backtest"

View File

@ -53,7 +53,7 @@ docker build --cache-from freqtrade:${TAG} --build-arg sourceimage=${CACHE_IMAGE
docker tag freqtrade:$TAG_PLOT ${CACHE_IMAGE}:$TAG_PLOT docker tag freqtrade:$TAG_PLOT ${CACHE_IMAGE}:$TAG_PLOT
# Run backtest # Run backtest
docker run --rm -v $(pwd)/config_examples/config_bittrex.example.json:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG} backtesting --datadir /tests/testdata --strategy-path /tests/strategy/strats/ --strategy StrategyTestV2 docker run --rm -v $(pwd)/config_examples/config_bittrex.example.json:/freqtrade/config.json:ro -v $(pwd)/tests:/tests freqtrade:${TAG} backtesting --datadir /tests/testdata --strategy-path /tests/strategy/strats/ --strategy StrategyTestV3
if [ $? -ne 0 ]; then if [ $? -ne 0 ]; then
echo "failed running backtest" echo "failed running backtest"

View File

@ -19,8 +19,8 @@ from freqtrade.commands.deploy_commands import (clean_ui_subdir, download_and_in
from freqtrade.configuration import setup_utils_configuration from freqtrade.configuration import setup_utils_configuration
from freqtrade.enums import RunMode from freqtrade.enums import RunMode
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import OperationalException
from tests.conftest import (create_mock_trades, get_args, log_has, log_has_re, patch_exchange, from tests.conftest import (CURRENT_TEST_STRATEGY, create_mock_trades, get_args, log_has,
patched_configuration_load_config_file) log_has_re, patch_exchange, patched_configuration_load_config_file)
from tests.conftest_trades import MOCK_TRADE_COUNT from tests.conftest_trades import MOCK_TRADE_COUNT
@ -774,7 +774,7 @@ def test_start_list_strategies(mocker, caplog, capsys):
captured = capsys.readouterr() captured = capsys.readouterr()
assert "TestStrategyLegacyV1" in captured.out assert "TestStrategyLegacyV1" in captured.out
assert "legacy_strategy_v1.py" not in captured.out assert "legacy_strategy_v1.py" not in captured.out
assert "StrategyTestV2" in captured.out assert CURRENT_TEST_STRATEGY in captured.out
# Test regular output # Test regular output
args = [ args = [
@ -789,7 +789,7 @@ def test_start_list_strategies(mocker, caplog, capsys):
captured = capsys.readouterr() captured = capsys.readouterr()
assert "TestStrategyLegacyV1" in captured.out assert "TestStrategyLegacyV1" in captured.out
assert "legacy_strategy_v1.py" in captured.out assert "legacy_strategy_v1.py" in captured.out
assert "StrategyTestV2" in captured.out assert CURRENT_TEST_STRATEGY in captured.out
# Test color output # Test color output
args = [ args = [
@ -803,7 +803,7 @@ def test_start_list_strategies(mocker, caplog, capsys):
captured = capsys.readouterr() captured = capsys.readouterr()
assert "TestStrategyLegacyV1" in captured.out assert "TestStrategyLegacyV1" in captured.out
assert "legacy_strategy_v1.py" in captured.out assert "legacy_strategy_v1.py" in captured.out
assert "StrategyTestV2" in captured.out assert CURRENT_TEST_STRATEGY in captured.out
assert "LOAD FAILED" in captured.out assert "LOAD FAILED" in captured.out

View File

@ -35,6 +35,8 @@ logging.getLogger('').setLevel(logging.INFO)
# Do not mask numpy errors as warnings that no one read, raise the exсeption # Do not mask numpy errors as warnings that no one read, raise the exсeption
np.seterr(all='raise') np.seterr(all='raise')
CURRENT_TEST_STRATEGY = 'StrategyTestV3'
def pytest_addoption(parser): def pytest_addoption(parser):
parser.addoption('--longrun', action='store_true', dest="longrun", parser.addoption('--longrun', action='store_true', dest="longrun",
@ -406,7 +408,7 @@ def get_default_conf(testdatadir):
"user_data_dir": Path("user_data"), "user_data_dir": Path("user_data"),
"verbosity": 3, "verbosity": 3,
"strategy_path": str(Path(__file__).parent / "strategy" / "strats"), "strategy_path": str(Path(__file__).parent / "strategy" / "strats"),
"strategy": "StrategyTestV2", "strategy": CURRENT_TEST_STRATEGY,
"disableparamexport": True, "disableparamexport": True,
"internals": {}, "internals": {},
"export": "none", "export": "none",

View File

@ -33,7 +33,7 @@ def mock_trade_1(fee):
open_rate=0.123, open_rate=0.123,
exchange='binance', exchange='binance',
open_order_id='dry_run_buy_12345', open_order_id='dry_run_buy_12345',
strategy='StrategyTestV2', strategy='StrategyTestV3',
timeframe=5, timeframe=5,
) )
o = Order.parse_from_ccxt_object(mock_order_1(), 'ETH/BTC', 'buy') o = Order.parse_from_ccxt_object(mock_order_1(), 'ETH/BTC', 'buy')
@ -87,7 +87,7 @@ def mock_trade_2(fee):
exchange='binance', exchange='binance',
is_open=False, is_open=False,
open_order_id='dry_run_sell_12345', open_order_id='dry_run_sell_12345',
strategy='StrategyTestV2', strategy='StrategyTestV3',
timeframe=5, timeframe=5,
sell_reason='sell_signal', sell_reason='sell_signal',
open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=20), open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=20),
@ -146,7 +146,7 @@ def mock_trade_3(fee):
close_profit_abs=0.000155, close_profit_abs=0.000155,
exchange='binance', exchange='binance',
is_open=False, is_open=False,
strategy='StrategyTestV2', strategy='StrategyTestV3',
timeframe=5, timeframe=5,
sell_reason='roi', sell_reason='roi',
open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=20), open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=20),
@ -189,7 +189,7 @@ def mock_trade_4(fee):
open_rate=0.123, open_rate=0.123,
exchange='binance', exchange='binance',
open_order_id='prod_buy_12345', open_order_id='prod_buy_12345',
strategy='StrategyTestV2', strategy='StrategyTestV3',
timeframe=5, timeframe=5,
) )
o = Order.parse_from_ccxt_object(mock_order_4(), 'ETC/BTC', 'buy') o = Order.parse_from_ccxt_object(mock_order_4(), 'ETC/BTC', 'buy')

View File

@ -16,7 +16,7 @@ from freqtrade.data.btanalysis import (BT_DATA_COLUMNS, BT_DATA_COLUMNS_MID, BT_
get_latest_hyperopt_file, load_backtest_data, load_trades, get_latest_hyperopt_file, load_backtest_data, load_trades,
load_trades_from_db) load_trades_from_db)
from freqtrade.data.history import load_data, load_pair_history from freqtrade.data.history import load_data, load_pair_history
from tests.conftest import create_mock_trades from tests.conftest import CURRENT_TEST_STRATEGY, create_mock_trades
from tests.conftest_trades import MOCK_TRADE_COUNT from tests.conftest_trades import MOCK_TRADE_COUNT
@ -128,7 +128,7 @@ def test_load_trades_from_db(default_conf, fee, mocker):
for col in BT_DATA_COLUMNS: for col in BT_DATA_COLUMNS:
if col not in ['index', 'open_at_end']: if col not in ['index', 'open_at_end']:
assert col in trades.columns assert col in trades.columns
trades = load_trades_from_db(db_url=default_conf['db_url'], strategy='StrategyTestV2') trades = load_trades_from_db(db_url=default_conf['db_url'], strategy=CURRENT_TEST_STRATEGY)
assert len(trades) == 4 assert len(trades) == 4
trades = load_trades_from_db(db_url=default_conf['db_url'], strategy='NoneStrategy') trades = load_trades_from_db(db_url=default_conf['db_url'], strategy='NoneStrategy')
assert len(trades) == 0 assert len(trades) == 0
@ -186,7 +186,7 @@ def test_load_trades(default_conf, mocker):
db_url=default_conf.get('db_url'), db_url=default_conf.get('db_url'),
exportfilename=default_conf.get('exportfilename'), exportfilename=default_conf.get('exportfilename'),
no_trades=False, no_trades=False,
strategy="StrategyTestV2", strategy=CURRENT_TEST_STRATEGY,
) )
assert db_mock.call_count == 1 assert db_mock.call_count == 1

View File

@ -26,7 +26,8 @@ from freqtrade.data.history.jsondatahandler import JsonDataHandler, JsonGzDataHa
from freqtrade.exchange import timeframe_to_minutes from freqtrade.exchange import timeframe_to_minutes
from freqtrade.misc import file_dump_json from freqtrade.misc import file_dump_json
from freqtrade.resolvers import StrategyResolver from freqtrade.resolvers import StrategyResolver
from tests.conftest import get_patched_exchange, log_has, log_has_re, patch_exchange from tests.conftest import (CURRENT_TEST_STRATEGY, get_patched_exchange, log_has, log_has_re,
patch_exchange)
# Change this if modifying UNITTEST/BTC testdatafile # Change this if modifying UNITTEST/BTC testdatafile
@ -380,7 +381,7 @@ def test_file_dump_json_tofile(testdatadir) -> None:
def test_get_timerange(default_conf, mocker, testdatadir) -> None: def test_get_timerange(default_conf, mocker, testdatadir) -> None:
patch_exchange(mocker) patch_exchange(mocker)
default_conf.update({'strategy': 'StrategyTestV2'}) default_conf.update({'strategy': CURRENT_TEST_STRATEGY})
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
data = strategy.advise_all_indicators( data = strategy.advise_all_indicators(
@ -398,7 +399,7 @@ def test_get_timerange(default_conf, mocker, testdatadir) -> None:
def test_validate_backtest_data_warn(default_conf, mocker, caplog, testdatadir) -> None: def test_validate_backtest_data_warn(default_conf, mocker, caplog, testdatadir) -> None:
patch_exchange(mocker) patch_exchange(mocker)
default_conf.update({'strategy': 'StrategyTestV2'}) default_conf.update({'strategy': CURRENT_TEST_STRATEGY})
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
data = strategy.advise_all_indicators( data = strategy.advise_all_indicators(
@ -422,7 +423,7 @@ def test_validate_backtest_data_warn(default_conf, mocker, caplog, testdatadir)
def test_validate_backtest_data(default_conf, mocker, caplog, testdatadir) -> None: def test_validate_backtest_data(default_conf, mocker, caplog, testdatadir) -> None:
patch_exchange(mocker) patch_exchange(mocker)
default_conf.update({'strategy': 'StrategyTestV2'}) default_conf.update({'strategy': CURRENT_TEST_STRATEGY})
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
timerange = TimeRange('index', 'index', 200, 250) timerange = TimeRange('index', 'index', 200, 250)

View File

@ -22,7 +22,7 @@ from freqtrade.exceptions import DependencyException, OperationalException
from freqtrade.optimize.backtesting import Backtesting from freqtrade.optimize.backtesting import Backtesting
from freqtrade.persistence import LocalTrade from freqtrade.persistence import LocalTrade
from freqtrade.resolvers import StrategyResolver from freqtrade.resolvers import StrategyResolver
from tests.conftest import (get_args, log_has, log_has_re, patch_exchange, from tests.conftest import (CURRENT_TEST_STRATEGY, get_args, log_has, log_has_re, patch_exchange,
patched_configuration_load_config_file) patched_configuration_load_config_file)
@ -159,7 +159,7 @@ def test_setup_optimize_configuration_without_arguments(mocker, default_conf, ca
args = [ args = [
'backtesting', 'backtesting',
'--config', 'config.json', '--config', 'config.json',
'--strategy', 'StrategyTestV2', '--strategy', CURRENT_TEST_STRATEGY,
'--export', 'none' '--export', 'none'
] ]
@ -194,7 +194,7 @@ def test_setup_bt_configuration_with_arguments(mocker, default_conf, caplog) ->
args = [ args = [
'backtesting', 'backtesting',
'--config', 'config.json', '--config', 'config.json',
'--strategy', 'StrategyTestV2', '--strategy', CURRENT_TEST_STRATEGY,
'--datadir', '/foo/bar', '--datadir', '/foo/bar',
'--timeframe', '1m', '--timeframe', '1m',
'--enable-position-stacking', '--enable-position-stacking',
@ -244,7 +244,7 @@ def test_setup_optimize_configuration_stake_amount(mocker, default_conf, caplog)
args = [ args = [
'backtesting', 'backtesting',
'--config', 'config.json', '--config', 'config.json',
'--strategy', 'StrategyTestV2', '--strategy', CURRENT_TEST_STRATEGY,
'--stake-amount', '1', '--stake-amount', '1',
'--starting-balance', '2' '--starting-balance', '2'
] ]
@ -255,7 +255,7 @@ def test_setup_optimize_configuration_stake_amount(mocker, default_conf, caplog)
args = [ args = [
'backtesting', 'backtesting',
'--config', 'config.json', '--config', 'config.json',
'--strategy', 'StrategyTestV2', '--strategy', CURRENT_TEST_STRATEGY,
'--stake-amount', '1', '--stake-amount', '1',
'--starting-balance', '0.5' '--starting-balance', '0.5'
] ]
@ -273,7 +273,7 @@ def test_start(mocker, fee, default_conf, caplog) -> None:
args = [ args = [
'backtesting', 'backtesting',
'--config', 'config.json', '--config', 'config.json',
'--strategy', 'StrategyTestV2', '--strategy', CURRENT_TEST_STRATEGY,
] ]
pargs = get_args(args) pargs = get_args(args)
start_backtesting(pargs) start_backtesting(pargs)
@ -306,7 +306,7 @@ def test_backtesting_init(mocker, default_conf, order_types) -> None:
def test_backtesting_init_no_timeframe(mocker, default_conf, caplog) -> None: def test_backtesting_init_no_timeframe(mocker, default_conf, caplog) -> None:
patch_exchange(mocker) patch_exchange(mocker)
del default_conf['timeframe'] del default_conf['timeframe']
default_conf['strategy_list'] = ['StrategyTestV2', default_conf['strategy_list'] = [CURRENT_TEST_STRATEGY,
'SampleStrategy'] 'SampleStrategy']
mocker.patch('freqtrade.exchange.Exchange.get_fee', MagicMock(return_value=0.5)) mocker.patch('freqtrade.exchange.Exchange.get_fee', MagicMock(return_value=0.5))
@ -344,7 +344,6 @@ def test_data_to_dataframe_bt(default_conf, mocker, testdatadir) -> None:
assert len(processed['UNITTEST/BTC']) == 102 assert len(processed['UNITTEST/BTC']) == 102
# Load strategy to compare the result between Backtesting function and strategy are the same # Load strategy to compare the result between Backtesting function and strategy are the same
default_conf.update({'strategy': 'StrategyTestV2'})
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
processed2 = strategy.advise_all_indicators(data) processed2 = strategy.advise_all_indicators(data)
@ -486,7 +485,7 @@ def test_backtesting_pairlist_list(default_conf, mocker, caplog, testdatadir, ti
Backtesting(default_conf) Backtesting(default_conf)
# Multiple strategies # Multiple strategies
default_conf['strategy_list'] = ['StrategyTestV2', 'TestStrategyLegacyV1'] default_conf['strategy_list'] = [CURRENT_TEST_STRATEGY, 'TestStrategyLegacyV1']
with pytest.raises(OperationalException, with pytest.raises(OperationalException,
match='PrecisionFilter not allowed for backtesting multiple strategies.'): match='PrecisionFilter not allowed for backtesting multiple strategies.'):
Backtesting(default_conf) Backtesting(default_conf)
@ -803,7 +802,7 @@ def test_backtest_pricecontours(default_conf, fee, mocker, testdatadir,
def test_backtest_clash_buy_sell(mocker, default_conf, testdatadir): def test_backtest_clash_buy_sell(mocker, default_conf, testdatadir):
# Override the default buy trend function in our StrategyTestV2 # Override the default buy trend function in our StrategyTest
def fun(dataframe=None, pair=None): def fun(dataframe=None, pair=None):
buy_value = 1 buy_value = 1
sell_value = 1 sell_value = 1
@ -819,7 +818,7 @@ def test_backtest_clash_buy_sell(mocker, default_conf, testdatadir):
def test_backtest_only_sell(mocker, default_conf, testdatadir): def test_backtest_only_sell(mocker, default_conf, testdatadir):
# Override the default buy trend function in our StrategyTestV2 # Override the default buy trend function in our StrategyTest
def fun(dataframe=None, pair=None): def fun(dataframe=None, pair=None):
buy_value = 0 buy_value = 0
sell_value = 1 sell_value = 1
@ -948,7 +947,7 @@ def test_backtest_start_timerange(default_conf, mocker, caplog, testdatadir):
args = [ args = [
'backtesting', 'backtesting',
'--config', 'config.json', '--config', 'config.json',
'--strategy', 'StrategyTestV2', '--strategy', CURRENT_TEST_STRATEGY,
'--datadir', str(testdatadir), '--datadir', str(testdatadir),
'--timeframe', '1m', '--timeframe', '1m',
'--timerange', '1510694220-1510700340', '--timerange', '1510694220-1510700340',
@ -1019,7 +1018,7 @@ def test_backtest_start_multi_strat(default_conf, mocker, caplog, testdatadir):
'--enable-position-stacking', '--enable-position-stacking',
'--disable-max-market-positions', '--disable-max-market-positions',
'--strategy-list', '--strategy-list',
'StrategyTestV2', CURRENT_TEST_STRATEGY,
'TestStrategyLegacyV1', 'TestStrategyLegacyV1',
] ]
args = get_args(args) args = get_args(args)
@ -1042,7 +1041,7 @@ def test_backtest_start_multi_strat(default_conf, mocker, caplog, testdatadir):
'Backtesting with data from 2017-11-14 21:17:00 ' 'Backtesting with data from 2017-11-14 21:17:00 '
'up to 2017-11-14 22:58:00 (0 days).', 'up to 2017-11-14 22:58:00 (0 days).',
'Parameter --enable-position-stacking detected ...', 'Parameter --enable-position-stacking detected ...',
'Running backtesting for Strategy StrategyTestV2', f'Running backtesting for Strategy {CURRENT_TEST_STRATEGY}',
'Running backtesting for Strategy TestStrategyLegacyV1', 'Running backtesting for Strategy TestStrategyLegacyV1',
] ]
@ -1123,7 +1122,7 @@ def test_backtest_start_multi_strat_nomock(default_conf, mocker, caplog, testdat
'--enable-position-stacking', '--enable-position-stacking',
'--disable-max-market-positions', '--disable-max-market-positions',
'--strategy-list', '--strategy-list',
'StrategyTestV2', CURRENT_TEST_STRATEGY,
'TestStrategyLegacyV1', 'TestStrategyLegacyV1',
] ]
args = get_args(args) args = get_args(args)
@ -1140,7 +1139,7 @@ def test_backtest_start_multi_strat_nomock(default_conf, mocker, caplog, testdat
'Backtesting with data from 2017-11-14 21:17:00 ' 'Backtesting with data from 2017-11-14 21:17:00 '
'up to 2017-11-14 22:58:00 (0 days).', 'up to 2017-11-14 22:58:00 (0 days).',
'Parameter --enable-position-stacking detected ...', 'Parameter --enable-position-stacking detected ...',
'Running backtesting for Strategy StrategyTestV2', f'Running backtesting for Strategy {CURRENT_TEST_STRATEGY}',
'Running backtesting for Strategy TestStrategyLegacyV1', 'Running backtesting for Strategy TestStrategyLegacyV1',
] ]
@ -1228,7 +1227,7 @@ def test_backtest_start_multi_strat_nomock_detail(default_conf, mocker,
'--timeframe', '5m', '--timeframe', '5m',
'--timeframe-detail', '1m', '--timeframe-detail', '1m',
'--strategy-list', '--strategy-list',
'StrategyTestV2' CURRENT_TEST_STRATEGY
] ]
args = get_args(args) args = get_args(args)
start_backtesting(args) start_backtesting(args)
@ -1242,7 +1241,7 @@ def test_backtest_start_multi_strat_nomock_detail(default_conf, mocker,
'up to 2019-10-13 11:10:00 (2 days).', 'up to 2019-10-13 11:10:00 (2 days).',
'Backtesting with data from 2019-10-11 01:40:00 ' 'Backtesting with data from 2019-10-11 01:40:00 '
'up to 2019-10-13 11:10:00 (2 days).', 'up to 2019-10-13 11:10:00 (2 days).',
'Running backtesting for Strategy StrategyTestV2', f'Running backtesting for Strategy {CURRENT_TEST_STRATEGY}',
] ]
for line in exists: for line in exists:

View File

@ -6,7 +6,7 @@ from unittest.mock import MagicMock
from freqtrade.commands.optimize_commands import setup_optimize_configuration, start_edge from freqtrade.commands.optimize_commands import setup_optimize_configuration, start_edge
from freqtrade.enums import RunMode from freqtrade.enums import RunMode
from freqtrade.optimize.edge_cli import EdgeCli from freqtrade.optimize.edge_cli import EdgeCli
from tests.conftest import (get_args, log_has, log_has_re, patch_exchange, from tests.conftest import (CURRENT_TEST_STRATEGY, get_args, log_has, log_has_re, patch_exchange,
patched_configuration_load_config_file) patched_configuration_load_config_file)
@ -16,7 +16,7 @@ def test_setup_optimize_configuration_without_arguments(mocker, default_conf, ca
args = [ args = [
'edge', 'edge',
'--config', 'config.json', '--config', 'config.json',
'--strategy', 'StrategyTestV2', '--strategy', CURRENT_TEST_STRATEGY,
] ]
config = setup_optimize_configuration(get_args(args), RunMode.EDGE) config = setup_optimize_configuration(get_args(args), RunMode.EDGE)
@ -46,7 +46,7 @@ def test_setup_edge_configuration_with_arguments(mocker, edge_conf, caplog) -> N
args = [ args = [
'edge', 'edge',
'--config', 'config.json', '--config', 'config.json',
'--strategy', 'StrategyTestV2', '--strategy', CURRENT_TEST_STRATEGY,
'--datadir', '/foo/bar', '--datadir', '/foo/bar',
'--timeframe', '1m', '--timeframe', '1m',
'--timerange', ':100', '--timerange', ':100',
@ -80,7 +80,7 @@ def test_start(mocker, fee, edge_conf, caplog) -> None:
args = [ args = [
'edge', 'edge',
'--config', 'config.json', '--config', 'config.json',
'--strategy', 'StrategyTestV2', '--strategy', CURRENT_TEST_STRATEGY,
] ]
pargs = get_args(args) pargs = get_args(args)
start_edge(pargs) start_edge(pargs)

View File

@ -18,7 +18,7 @@ from freqtrade.optimize.hyperopt_tools import HyperoptTools
from freqtrade.optimize.optimize_reports import generate_strategy_stats from freqtrade.optimize.optimize_reports import generate_strategy_stats
from freqtrade.optimize.space import SKDecimal from freqtrade.optimize.space import SKDecimal
from freqtrade.strategy.hyper import IntParameter from freqtrade.strategy.hyper import IntParameter
from tests.conftest import (get_args, log_has, log_has_re, patch_exchange, from tests.conftest import (CURRENT_TEST_STRATEGY, get_args, log_has, log_has_re, patch_exchange,
patched_configuration_load_config_file) patched_configuration_load_config_file)
@ -125,7 +125,7 @@ def test_setup_hyperopt_configuration_stake_amount(mocker, default_conf) -> None
args = [ args = [
'hyperopt', 'hyperopt',
'--config', 'config.json', '--config', 'config.json',
'--strategy', 'StrategyTestV2', '--strategy', CURRENT_TEST_STRATEGY,
'--stake-amount', '1', '--stake-amount', '1',
'--starting-balance', '0.5' '--starting-balance', '0.5'
] ]

View File

@ -10,7 +10,7 @@ import rapidjson
from freqtrade.constants import FTHYPT_FILEVERSION from freqtrade.constants import FTHYPT_FILEVERSION
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import OperationalException
from freqtrade.optimize.hyperopt_tools import HyperoptTools, hyperopt_serializer from freqtrade.optimize.hyperopt_tools import HyperoptTools, hyperopt_serializer
from tests.conftest import log_has from tests.conftest import CURRENT_TEST_STRATEGY, log_has
# Functions for recurrent object patching # Functions for recurrent object patching
@ -167,9 +167,9 @@ def test__pprint_dict():
def test_get_strategy_filename(default_conf): def test_get_strategy_filename(default_conf):
x = HyperoptTools.get_strategy_filename(default_conf, 'StrategyTestV2') x = HyperoptTools.get_strategy_filename(default_conf, CURRENT_TEST_STRATEGY)
assert isinstance(x, Path) assert isinstance(x, Path)
assert x == Path(__file__).parents[1] / 'strategy/strats/strategy_test_v2.py' assert x == Path(__file__).parents[1] / 'strategy/strats/strategy_test_v3.py'
x = HyperoptTools.get_strategy_filename(default_conf, 'NonExistingStrategy') x = HyperoptTools.get_strategy_filename(default_conf, 'NonExistingStrategy')
assert x is None assert x is None
@ -177,7 +177,7 @@ def test_get_strategy_filename(default_conf):
def test_export_params(tmpdir): def test_export_params(tmpdir):
filename = Path(tmpdir) / "StrategyTestV2.json" filename = Path(tmpdir) / f"{CURRENT_TEST_STRATEGY}.json"
assert not filename.is_file() assert not filename.is_file()
params = { params = {
"params_details": { "params_details": {
@ -205,12 +205,12 @@ def test_export_params(tmpdir):
} }
} }
HyperoptTools.export_params(params, "StrategyTestV2", filename) HyperoptTools.export_params(params, CURRENT_TEST_STRATEGY, filename)
assert filename.is_file() assert filename.is_file()
content = rapidjson.load(filename.open('r')) content = rapidjson.load(filename.open('r'))
assert content['strategy_name'] == 'StrategyTestV2' assert content['strategy_name'] == CURRENT_TEST_STRATEGY
assert 'params' in content assert 'params' in content
assert "buy" in content["params"] assert "buy" in content["params"]
assert "sell" in content["params"] assert "sell" in content["params"]
@ -223,7 +223,7 @@ def test_try_export_params(default_conf, tmpdir, caplog, mocker):
default_conf['disableparamexport'] = False default_conf['disableparamexport'] = False
export_mock = mocker.patch("freqtrade.optimize.hyperopt_tools.HyperoptTools.export_params") export_mock = mocker.patch("freqtrade.optimize.hyperopt_tools.HyperoptTools.export_params")
filename = Path(tmpdir) / "StrategyTestV2.json" filename = Path(tmpdir) / f"{CURRENT_TEST_STRATEGY}.json"
assert not filename.is_file() assert not filename.is_file()
params = { params = {
"params_details": { "params_details": {
@ -252,17 +252,17 @@ def test_try_export_params(default_conf, tmpdir, caplog, mocker):
FTHYPT_FILEVERSION: 2, FTHYPT_FILEVERSION: 2,
} }
HyperoptTools.try_export_params(default_conf, "StrategyTestV222", params) HyperoptTools.try_export_params(default_conf, "StrategyTestVXXX", params)
assert log_has("Strategy not found, not exporting parameter file.", caplog) assert log_has("Strategy not found, not exporting parameter file.", caplog)
assert export_mock.call_count == 0 assert export_mock.call_count == 0
caplog.clear() caplog.clear()
HyperoptTools.try_export_params(default_conf, "StrategyTestV2", params) HyperoptTools.try_export_params(default_conf, CURRENT_TEST_STRATEGY, params)
assert export_mock.call_count == 1 assert export_mock.call_count == 1
assert export_mock.call_args_list[0][0][1] == 'StrategyTestV2' assert export_mock.call_args_list[0][0][1] == CURRENT_TEST_STRATEGY
assert export_mock.call_args_list[0][0][2].name == 'strategy_test_v2.json' assert export_mock.call_args_list[0][0][2].name == 'strategy_test_v3.json'
def test_params_print(capsys): def test_params_print(capsys):

View File

@ -21,6 +21,7 @@ from freqtrade.optimize.optimize_reports import (generate_backtest_stats, genera
text_table_bt_results, text_table_sell_reason, text_table_bt_results, text_table_sell_reason,
text_table_strategy) text_table_strategy)
from freqtrade.resolvers.strategy_resolver import StrategyResolver from freqtrade.resolvers.strategy_resolver import StrategyResolver
from tests.conftest import CURRENT_TEST_STRATEGY
from tests.data.test_history import _backup_file, _clean_test_file from tests.data.test_history import _backup_file, _clean_test_file
@ -52,7 +53,7 @@ def test_text_table_bt_results():
def test_generate_backtest_stats(default_conf, testdatadir, tmpdir): def test_generate_backtest_stats(default_conf, testdatadir, tmpdir):
default_conf.update({'strategy': 'StrategyTestV2'}) default_conf.update({'strategy': CURRENT_TEST_STRATEGY})
StrategyResolver.load_strategy(default_conf) StrategyResolver.load_strategy(default_conf)
results = {'DefStrat': { results = {'DefStrat': {

View File

@ -24,8 +24,8 @@ from freqtrade.rpc import RPC
from freqtrade.rpc.api_server import ApiServer from freqtrade.rpc.api_server import ApiServer
from freqtrade.rpc.api_server.api_auth import create_token, get_user_from_token from freqtrade.rpc.api_server.api_auth import create_token, get_user_from_token
from freqtrade.rpc.api_server.uvicorn_threaded import UvicornServer from freqtrade.rpc.api_server.uvicorn_threaded import UvicornServer
from tests.conftest import (create_mock_trades, get_mock_coro, get_patched_freqtradebot, log_has, from tests.conftest import (CURRENT_TEST_STRATEGY, create_mock_trades, get_mock_coro,
log_has_re, patch_get_signal) get_patched_freqtradebot, log_has, log_has_re, patch_get_signal)
BASE_URI = "/api/v1" BASE_URI = "/api/v1"
@ -885,7 +885,7 @@ def test_api_status(botclient, mocker, ticker, fee, markets):
'open_trade_value': 15.1668225, 'open_trade_value': 15.1668225,
'sell_reason': None, 'sell_reason': None,
'sell_order_status': None, 'sell_order_status': None,
'strategy': 'StrategyTestV2', 'strategy': CURRENT_TEST_STRATEGY,
'buy_tag': None, 'buy_tag': None,
'timeframe': 5, 'timeframe': 5,
'exchange': 'binance', 'exchange': 'binance',
@ -990,7 +990,7 @@ def test_api_forcebuy(botclient, mocker, fee):
close_rate=0.265441, close_rate=0.265441,
id=22, id=22,
timeframe=5, timeframe=5,
strategy="StrategyTestV2" strategy=CURRENT_TEST_STRATEGY
)) ))
mocker.patch("freqtrade.rpc.RPC._rpc_forcebuy", fbuy_mock) mocker.patch("freqtrade.rpc.RPC._rpc_forcebuy", fbuy_mock)
@ -1040,7 +1040,7 @@ def test_api_forcebuy(botclient, mocker, fee):
'open_trade_value': 0.24605460, 'open_trade_value': 0.24605460,
'sell_reason': None, 'sell_reason': None,
'sell_order_status': None, 'sell_order_status': None,
'strategy': 'StrategyTestV2', 'strategy': CURRENT_TEST_STRATEGY,
'buy_tag': None, 'buy_tag': None,
'timeframe': 5, 'timeframe': 5,
'exchange': 'binance', 'exchange': 'binance',
@ -1107,7 +1107,7 @@ def test_api_pair_candles(botclient, ohlcv_history):
f"{BASE_URI}/pair_candles?limit={amount}&pair=XRP%2FBTC&timeframe={timeframe}") f"{BASE_URI}/pair_candles?limit={amount}&pair=XRP%2FBTC&timeframe={timeframe}")
assert_response(rc) assert_response(rc)
assert 'strategy' in rc.json() assert 'strategy' in rc.json()
assert rc.json()['strategy'] == 'StrategyTestV2' assert rc.json()['strategy'] == CURRENT_TEST_STRATEGY
assert 'columns' in rc.json() assert 'columns' in rc.json()
assert 'data_start_ts' in rc.json() assert 'data_start_ts' in rc.json()
assert 'data_start' in rc.json() assert 'data_start' in rc.json()
@ -1145,19 +1145,19 @@ def test_api_pair_history(botclient, ohlcv_history):
# No pair # No pair
rc = client_get(client, rc = client_get(client,
f"{BASE_URI}/pair_history?timeframe={timeframe}" f"{BASE_URI}/pair_history?timeframe={timeframe}"
"&timerange=20180111-20180112&strategy=StrategyTestV2") f"&timerange=20180111-20180112&strategy={CURRENT_TEST_STRATEGY}")
assert_response(rc, 422) assert_response(rc, 422)
# No Timeframe # No Timeframe
rc = client_get(client, rc = client_get(client,
f"{BASE_URI}/pair_history?pair=UNITTEST%2FBTC" f"{BASE_URI}/pair_history?pair=UNITTEST%2FBTC"
"&timerange=20180111-20180112&strategy=StrategyTestV2") f"&timerange=20180111-20180112&strategy={CURRENT_TEST_STRATEGY}")
assert_response(rc, 422) assert_response(rc, 422)
# No timerange # No timerange
rc = client_get(client, rc = client_get(client,
f"{BASE_URI}/pair_history?pair=UNITTEST%2FBTC&timeframe={timeframe}" f"{BASE_URI}/pair_history?pair=UNITTEST%2FBTC&timeframe={timeframe}"
"&strategy=StrategyTestV2") f"&strategy={CURRENT_TEST_STRATEGY}")
assert_response(rc, 422) assert_response(rc, 422)
# No strategy # No strategy
@ -1169,14 +1169,14 @@ def test_api_pair_history(botclient, ohlcv_history):
# Working # Working
rc = client_get(client, rc = client_get(client,
f"{BASE_URI}/pair_history?pair=UNITTEST%2FBTC&timeframe={timeframe}" f"{BASE_URI}/pair_history?pair=UNITTEST%2FBTC&timeframe={timeframe}"
"&timerange=20180111-20180112&strategy=StrategyTestV2") f"&timerange=20180111-20180112&strategy={CURRENT_TEST_STRATEGY}")
assert_response(rc, 200) assert_response(rc, 200)
assert rc.json()['length'] == 289 assert rc.json()['length'] == 289
assert len(rc.json()['data']) == rc.json()['length'] assert len(rc.json()['data']) == rc.json()['length']
assert 'columns' in rc.json() assert 'columns' in rc.json()
assert 'data' in rc.json() assert 'data' in rc.json()
assert rc.json()['pair'] == 'UNITTEST/BTC' assert rc.json()['pair'] == 'UNITTEST/BTC'
assert rc.json()['strategy'] == 'StrategyTestV2' assert rc.json()['strategy'] == CURRENT_TEST_STRATEGY
assert rc.json()['data_start'] == '2018-01-11 00:00:00+00:00' assert rc.json()['data_start'] == '2018-01-11 00:00:00+00:00'
assert rc.json()['data_start_ts'] == 1515628800000 assert rc.json()['data_start_ts'] == 1515628800000
assert rc.json()['data_stop'] == '2018-01-12 00:00:00+00:00' assert rc.json()['data_stop'] == '2018-01-12 00:00:00+00:00'
@ -1185,7 +1185,7 @@ def test_api_pair_history(botclient, ohlcv_history):
# No data found # No data found
rc = client_get(client, rc = client_get(client,
f"{BASE_URI}/pair_history?pair=UNITTEST%2FBTC&timeframe={timeframe}" f"{BASE_URI}/pair_history?pair=UNITTEST%2FBTC&timeframe={timeframe}"
"&timerange=20200111-20200112&strategy=StrategyTestV2") f"&timerange=20200111-20200112&strategy={CURRENT_TEST_STRATEGY}")
assert_response(rc, 502) assert_response(rc, 502)
assert rc.json()['error'] == ("Error querying /api/v1/pair_history: " assert rc.json()['error'] == ("Error querying /api/v1/pair_history: "
"No data for UNITTEST/BTC, 5m in 20200111-20200112 found.") "No data for UNITTEST/BTC, 5m in 20200111-20200112 found.")
@ -1234,12 +1234,12 @@ def test_api_strategies(botclient):
def test_api_strategy(botclient): def test_api_strategy(botclient):
ftbot, client = botclient ftbot, client = botclient
rc = client_get(client, f"{BASE_URI}/strategy/StrategyTestV2") rc = client_get(client, f"{BASE_URI}/strategy/{CURRENT_TEST_STRATEGY}")
assert_response(rc) assert_response(rc)
assert rc.json()['strategy'] == 'StrategyTestV2' assert rc.json()['strategy'] == CURRENT_TEST_STRATEGY
data = (Path(__file__).parents[1] / "strategy/strats/strategy_test_v2.py").read_text() data = (Path(__file__).parents[1] / "strategy/strats/strategy_test_v3.py").read_text()
assert rc.json()['code'] == data assert rc.json()['code'] == data
rc = client_get(client, f"{BASE_URI}/strategy/NoStrat") rc = client_get(client, f"{BASE_URI}/strategy/NoStrat")
@ -1296,7 +1296,7 @@ def test_api_backtesting(botclient, mocker, fee, caplog):
# start backtesting # start backtesting
data = { data = {
"strategy": "StrategyTestV2", "strategy": CURRENT_TEST_STRATEGY,
"timeframe": "5m", "timeframe": "5m",
"timerange": "20180110-20180111", "timerange": "20180110-20180111",
"max_open_trades": 3, "max_open_trades": 3,

View File

@ -25,8 +25,8 @@ from freqtrade.loggers import setup_logging
from freqtrade.persistence import PairLocks, Trade from freqtrade.persistence import PairLocks, Trade
from freqtrade.rpc import RPC from freqtrade.rpc import RPC
from freqtrade.rpc.telegram import Telegram, authorized_only from freqtrade.rpc.telegram import Telegram, authorized_only
from tests.conftest import (create_mock_trades, get_patched_freqtradebot, log_has, log_has_re, from tests.conftest import (CURRENT_TEST_STRATEGY, create_mock_trades, get_patched_freqtradebot,
patch_exchange, patch_get_signal, patch_whitelist) log_has, log_has_re, patch_exchange, patch_get_signal, patch_whitelist)
class DummyCls(Telegram): class DummyCls(Telegram):
@ -1238,7 +1238,7 @@ def test_show_config_handle(default_conf, update, mocker) -> None:
assert msg_mock.call_count == 1 assert msg_mock.call_count == 1
assert '*Mode:* `{}`'.format('Dry-run') in msg_mock.call_args_list[0][0][0] assert '*Mode:* `{}`'.format('Dry-run') in msg_mock.call_args_list[0][0][0]
assert '*Exchange:* `binance`' in msg_mock.call_args_list[0][0][0] assert '*Exchange:* `binance`' in msg_mock.call_args_list[0][0][0]
assert '*Strategy:* `StrategyTestV2`' in msg_mock.call_args_list[0][0][0] assert f'*Strategy:* `{CURRENT_TEST_STRATEGY}`' in msg_mock.call_args_list[0][0][0]
assert '*Stoploss:* `-0.1`' in msg_mock.call_args_list[0][0][0] assert '*Stoploss:* `-0.1`' in msg_mock.call_args_list[0][0][0]
msg_mock.reset_mock() msg_mock.reset_mock()
@ -1247,7 +1247,7 @@ def test_show_config_handle(default_conf, update, mocker) -> None:
assert msg_mock.call_count == 1 assert msg_mock.call_count == 1
assert '*Mode:* `{}`'.format('Dry-run') in msg_mock.call_args_list[0][0][0] assert '*Mode:* `{}`'.format('Dry-run') in msg_mock.call_args_list[0][0][0]
assert '*Exchange:* `binance`' in msg_mock.call_args_list[0][0][0] assert '*Exchange:* `binance`' in msg_mock.call_args_list[0][0][0]
assert '*Strategy:* `StrategyTestV2`' in msg_mock.call_args_list[0][0][0] assert f'*Strategy:* `{CURRENT_TEST_STRATEGY}`' in msg_mock.call_args_list[0][0][0]
assert '*Initial Stoploss:* `-0.1`' in msg_mock.call_args_list[0][0][0] assert '*Initial Stoploss:* `-0.1`' in msg_mock.call_args_list[0][0][0]

View File

@ -2,8 +2,7 @@
from pandas import DataFrame from pandas import DataFrame
from freqtrade.strategy import informative, merge_informative_pair from freqtrade.strategy import IStrategy, informative, merge_informative_pair
from freqtrade.strategy import IStrategy
class InformativeDecoratorTest(IStrategy): class InformativeDecoratorTest(IStrategy):

View File

@ -68,15 +68,17 @@ class StrategyTestV3(IStrategy):
protection_enabled = BooleanParameter(default=True) protection_enabled = BooleanParameter(default=True)
protection_cooldown_lookback = IntParameter([0, 50], default=30) protection_cooldown_lookback = IntParameter([0, 50], default=30)
@property # TODO-lev: Can we make this work with protection tests?
def protections(self): # TODO-lev: (Would replace HyperoptableStrategy implicitly ... )
prot = [] # @property
if self.protection_enabled.value: # def protections(self):
prot.append({ # prot = []
"method": "CooldownPeriod", # if self.protection_enabled.value:
"stop_duration_candles": self.protection_cooldown_lookback.value # prot.append({
}) # "method": "CooldownPeriod",
return prot # "stop_duration_candles": self.protection_cooldown_lookback.value
# })
# return prot
def informative_pairs(self): def informative_pairs(self):
@ -134,7 +136,7 @@ class StrategyTestV3(IStrategy):
(dataframe['adx'] > 65) & (dataframe['adx'] > 65) &
(dataframe['plus_di'] > self.buy_plusdi.value) (dataframe['plus_di'] > self.buy_plusdi.value)
), ),
'enter_trade'] = 1 'enter_long'] = 1
# TODO-lev: Add short logic # TODO-lev: Add short logic
return dataframe return dataframe
@ -153,7 +155,7 @@ class StrategyTestV3(IStrategy):
(dataframe['adx'] > 70) & (dataframe['adx'] > 70) &
(dataframe['minus_di'] > self.sell_minusdi.value) (dataframe['minus_di'] > self.sell_minusdi.value)
), ),
'exit_trade'] = 1 'exit_long'] = 1
# TODO-lev: Add short logic # TODO-lev: Add short logic
return dataframe return dataframe

View File

@ -4,20 +4,20 @@ from pandas import DataFrame
from freqtrade.persistence.models import Trade from freqtrade.persistence.models import Trade
from .strats.strategy_test_v2 import StrategyTestV2 from .strats.strategy_test_v3 import StrategyTestV3
def test_strategy_test_v2_structure(): def test_strategy_test_v2_structure():
assert hasattr(StrategyTestV2, 'minimal_roi') assert hasattr(StrategyTestV3, 'minimal_roi')
assert hasattr(StrategyTestV2, 'stoploss') assert hasattr(StrategyTestV3, 'stoploss')
assert hasattr(StrategyTestV2, 'timeframe') assert hasattr(StrategyTestV3, 'timeframe')
assert hasattr(StrategyTestV2, 'populate_indicators') assert hasattr(StrategyTestV3, 'populate_indicators')
assert hasattr(StrategyTestV2, 'populate_buy_trend') assert hasattr(StrategyTestV3, 'populate_buy_trend')
assert hasattr(StrategyTestV2, 'populate_sell_trend') assert hasattr(StrategyTestV3, 'populate_sell_trend')
def test_strategy_test_v2(result, fee): def test_strategy_test_v2(result, fee):
strategy = StrategyTestV2({}) strategy = StrategyTestV3({})
metadata = {'pair': 'ETH/BTC'} metadata = {'pair': 'ETH/BTC'}
assert type(strategy.minimal_roi) is dict assert type(strategy.minimal_roi) is dict

View File

@ -177,7 +177,6 @@ def test_get_signal_no_sell_column(default_conf, mocker, caplog, ohlcv_history):
def test_ignore_expired_candle(default_conf): def test_ignore_expired_candle(default_conf):
default_conf.update({'strategy': 'StrategyTestV2'})
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
strategy.ignore_buying_expired_candle_after = 60 strategy.ignore_buying_expired_candle_after = 60
@ -262,7 +261,6 @@ def test_assert_df(ohlcv_history, caplog):
def test_advise_all_indicators(default_conf, testdatadir) -> None: def test_advise_all_indicators(default_conf, testdatadir) -> None:
default_conf.update({'strategy': 'StrategyTestV2'})
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
timerange = TimeRange.parse_timerange('1510694220-1510700340') timerange = TimeRange.parse_timerange('1510694220-1510700340')
@ -273,7 +271,6 @@ def test_advise_all_indicators(default_conf, testdatadir) -> None:
def test_advise_all_indicators_copy(mocker, default_conf, testdatadir) -> None: def test_advise_all_indicators_copy(mocker, default_conf, testdatadir) -> None:
default_conf.update({'strategy': 'StrategyTestV2'})
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
aimock = mocker.patch('freqtrade.strategy.interface.IStrategy.advise_indicators') aimock = mocker.patch('freqtrade.strategy.interface.IStrategy.advise_indicators')
timerange = TimeRange.parse_timerange('1510694220-1510700340') timerange = TimeRange.parse_timerange('1510694220-1510700340')
@ -291,7 +288,6 @@ def test_min_roi_reached(default_conf, fee) -> None:
min_roi_list = [{20: 0.05, 55: 0.01, 0: 0.1}, min_roi_list = [{20: 0.05, 55: 0.01, 0: 0.1},
{0: 0.1, 20: 0.05, 55: 0.01}] {0: 0.1, 20: 0.05, 55: 0.01}]
for roi in min_roi_list: for roi in min_roi_list:
default_conf.update({'strategy': 'StrategyTestV2'})
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
strategy.minimal_roi = roi strategy.minimal_roi = roi
trade = Trade( trade = Trade(
@ -330,7 +326,6 @@ def test_min_roi_reached2(default_conf, fee) -> None:
}, },
] ]
for roi in min_roi_list: for roi in min_roi_list:
default_conf.update({'strategy': 'StrategyTestV2'})
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
strategy.minimal_roi = roi strategy.minimal_roi = roi
trade = Trade( trade = Trade(
@ -365,7 +360,6 @@ def test_min_roi_reached3(default_conf, fee) -> None:
30: 0.05, 30: 0.05,
55: 0.30, 55: 0.30,
} }
default_conf.update({'strategy': 'StrategyTestV2'})
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
strategy.minimal_roi = min_roi strategy.minimal_roi = min_roi
trade = Trade( trade = Trade(
@ -418,8 +412,6 @@ def test_min_roi_reached3(default_conf, fee) -> None:
def test_stop_loss_reached(default_conf, fee, profit, adjusted, expected, trailing, custom, def test_stop_loss_reached(default_conf, fee, profit, adjusted, expected, trailing, custom,
profit2, adjusted2, expected2, custom_stop) -> None: profit2, adjusted2, expected2, custom_stop) -> None:
default_conf.update({'strategy': 'StrategyTestV2'})
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
trade = Trade( trade = Trade(
pair='ETH/BTC', pair='ETH/BTC',
@ -466,8 +458,6 @@ def test_stop_loss_reached(default_conf, fee, profit, adjusted, expected, traili
def test_custom_sell(default_conf, fee, caplog) -> None: def test_custom_sell(default_conf, fee, caplog) -> None:
default_conf.update({'strategy': 'StrategyTestV2'})
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
trade = Trade( trade = Trade(
pair='ETH/BTC', pair='ETH/BTC',
@ -591,7 +581,6 @@ def test__analyze_ticker_internal_skip_analyze(ohlcv_history, mocker, caplog) ->
@pytest.mark.usefixtures("init_persistence") @pytest.mark.usefixtures("init_persistence")
def test_is_pair_locked(default_conf): def test_is_pair_locked(default_conf):
default_conf.update({'strategy': 'StrategyTestV2'})
PairLocks.timeframe = default_conf['timeframe'] PairLocks.timeframe = default_conf['timeframe']
PairLocks.use_db = True PairLocks.use_db = True
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)

View File

@ -10,7 +10,7 @@ from pandas import DataFrame
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import OperationalException
from freqtrade.resolvers import StrategyResolver from freqtrade.resolvers import StrategyResolver
from freqtrade.strategy.interface import IStrategy from freqtrade.strategy.interface import IStrategy
from tests.conftest import log_has, log_has_re from tests.conftest import CURRENT_TEST_STRATEGY, log_has, log_has_re
def test_search_strategy(): def test_search_strategy():
@ -18,7 +18,7 @@ def test_search_strategy():
s, _ = StrategyResolver._search_object( s, _ = StrategyResolver._search_object(
directory=default_location, directory=default_location,
object_name='StrategyTestV2', object_name=CURRENT_TEST_STRATEGY,
add_source=True, add_source=True,
) )
assert issubclass(s, IStrategy) assert issubclass(s, IStrategy)
@ -77,7 +77,7 @@ def test_load_strategy_invalid_directory(result, caplog, default_conf):
default_conf['strategy'] = 'StrategyTestV3' default_conf['strategy'] = 'StrategyTestV3'
extra_dir = Path.cwd() / 'some/path' extra_dir = Path.cwd() / 'some/path'
with pytest.raises(OperationalException): with pytest.raises(OperationalException):
StrategyResolver._load_strategy('StrategyTestV2', config=default_conf, StrategyResolver._load_strategy(CURRENT_TEST_STRATEGY, config=default_conf,
extra_dir=extra_dir) extra_dir=extra_dir)
assert log_has_re(r'Path .*' + r'some.*path.*' + r'.* does not exist', caplog) assert log_has_re(r'Path .*' + r'some.*path.*' + r'.* does not exist', caplog)
@ -129,7 +129,7 @@ def test_strategy_v2(result, default_conf):
def test_strategy_override_minimal_roi(caplog, default_conf): def test_strategy_override_minimal_roi(caplog, default_conf):
caplog.set_level(logging.INFO) caplog.set_level(logging.INFO)
default_conf.update({ default_conf.update({
'strategy': 'StrategyTestV3', 'strategy': CURRENT_TEST_STRATEGY,
'minimal_roi': { 'minimal_roi': {
"20": 0.1, "20": 0.1,
"0": 0.5 "0": 0.5
@ -146,7 +146,7 @@ def test_strategy_override_minimal_roi(caplog, default_conf):
def test_strategy_override_stoploss(caplog, default_conf): def test_strategy_override_stoploss(caplog, default_conf):
caplog.set_level(logging.INFO) caplog.set_level(logging.INFO)
default_conf.update({ default_conf.update({
'strategy': 'StrategyTestV3', 'strategy': CURRENT_TEST_STRATEGY,
'stoploss': -0.5 'stoploss': -0.5
}) })
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
@ -158,7 +158,7 @@ def test_strategy_override_stoploss(caplog, default_conf):
def test_strategy_override_trailing_stop(caplog, default_conf): def test_strategy_override_trailing_stop(caplog, default_conf):
caplog.set_level(logging.INFO) caplog.set_level(logging.INFO)
default_conf.update({ default_conf.update({
'strategy': 'StrategyTestV3', 'strategy': CURRENT_TEST_STRATEGY,
'trailing_stop': True 'trailing_stop': True
}) })
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
@ -171,7 +171,7 @@ def test_strategy_override_trailing_stop(caplog, default_conf):
def test_strategy_override_trailing_stop_positive(caplog, default_conf): def test_strategy_override_trailing_stop_positive(caplog, default_conf):
caplog.set_level(logging.INFO) caplog.set_level(logging.INFO)
default_conf.update({ default_conf.update({
'strategy': 'StrategyTestV3', 'strategy': CURRENT_TEST_STRATEGY,
'trailing_stop_positive': -0.1, 'trailing_stop_positive': -0.1,
'trailing_stop_positive_offset': -0.2 'trailing_stop_positive_offset': -0.2
@ -191,7 +191,7 @@ def test_strategy_override_timeframe(caplog, default_conf):
caplog.set_level(logging.INFO) caplog.set_level(logging.INFO)
default_conf.update({ default_conf.update({
'strategy': 'StrategyTestV3', 'strategy': CURRENT_TEST_STRATEGY,
'timeframe': 60, 'timeframe': 60,
'stake_currency': 'ETH' 'stake_currency': 'ETH'
}) })
@ -207,7 +207,7 @@ def test_strategy_override_process_only_new_candles(caplog, default_conf):
caplog.set_level(logging.INFO) caplog.set_level(logging.INFO)
default_conf.update({ default_conf.update({
'strategy': 'StrategyTestV3', 'strategy': CURRENT_TEST_STRATEGY,
'process_only_new_candles': True 'process_only_new_candles': True
}) })
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
@ -227,7 +227,7 @@ def test_strategy_override_order_types(caplog, default_conf):
'stoploss_on_exchange': True, 'stoploss_on_exchange': True,
} }
default_conf.update({ default_conf.update({
'strategy': 'StrategyTestV3', 'strategy': CURRENT_TEST_STRATEGY,
'order_types': order_types 'order_types': order_types
}) })
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
@ -241,12 +241,12 @@ def test_strategy_override_order_types(caplog, default_conf):
" 'stoploss_on_exchange': True}.", caplog) " 'stoploss_on_exchange': True}.", caplog)
default_conf.update({ default_conf.update({
'strategy': 'StrategyTestV3', 'strategy': CURRENT_TEST_STRATEGY,
'order_types': {'buy': 'market'} 'order_types': {'buy': 'market'}
}) })
# Raise error for invalid configuration # Raise error for invalid configuration
with pytest.raises(ImportError, with pytest.raises(ImportError,
match=r"Impossible to load Strategy 'StrategyTestV3'. " match=r"Impossible to load Strategy '" + CURRENT_TEST_STRATEGY + "'. "
r"Order-types mapping is incomplete."): r"Order-types mapping is incomplete."):
StrategyResolver.load_strategy(default_conf) StrategyResolver.load_strategy(default_conf)
@ -260,7 +260,7 @@ def test_strategy_override_order_tif(caplog, default_conf):
} }
default_conf.update({ default_conf.update({
'strategy': 'StrategyTestV3', 'strategy': CURRENT_TEST_STRATEGY,
'order_time_in_force': order_time_in_force 'order_time_in_force': order_time_in_force
}) })
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
@ -273,20 +273,20 @@ def test_strategy_override_order_tif(caplog, default_conf):
" {'buy': 'fok', 'sell': 'gtc'}.", caplog) " {'buy': 'fok', 'sell': 'gtc'}.", caplog)
default_conf.update({ default_conf.update({
'strategy': 'StrategyTestV3', 'strategy': CURRENT_TEST_STRATEGY,
'order_time_in_force': {'buy': 'fok'} 'order_time_in_force': {'buy': 'fok'}
}) })
# Raise error for invalid configuration # Raise error for invalid configuration
with pytest.raises(ImportError, with pytest.raises(ImportError,
match=r"Impossible to load Strategy 'StrategyTestV3'. " match=f"Impossible to load Strategy '{CURRENT_TEST_STRATEGY}'. "
r"Order-time-in-force mapping is incomplete."): "Order-time-in-force mapping is incomplete."):
StrategyResolver.load_strategy(default_conf) StrategyResolver.load_strategy(default_conf)
def test_strategy_override_use_sell_signal(caplog, default_conf): def test_strategy_override_use_sell_signal(caplog, default_conf):
caplog.set_level(logging.INFO) caplog.set_level(logging.INFO)
default_conf.update({ default_conf.update({
'strategy': 'StrategyTestV3', 'strategy': CURRENT_TEST_STRATEGY,
}) })
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
assert strategy.use_sell_signal assert strategy.use_sell_signal
@ -296,7 +296,7 @@ def test_strategy_override_use_sell_signal(caplog, default_conf):
assert default_conf['use_sell_signal'] assert default_conf['use_sell_signal']
default_conf.update({ default_conf.update({
'strategy': 'StrategyTestV3', 'strategy': CURRENT_TEST_STRATEGY,
'use_sell_signal': False, 'use_sell_signal': False,
}) })
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
@ -309,7 +309,7 @@ def test_strategy_override_use_sell_signal(caplog, default_conf):
def test_strategy_override_use_sell_profit_only(caplog, default_conf): def test_strategy_override_use_sell_profit_only(caplog, default_conf):
caplog.set_level(logging.INFO) caplog.set_level(logging.INFO)
default_conf.update({ default_conf.update({
'strategy': 'StrategyTestV3', 'strategy': CURRENT_TEST_STRATEGY,
}) })
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
assert not strategy.sell_profit_only assert not strategy.sell_profit_only
@ -319,7 +319,7 @@ def test_strategy_override_use_sell_profit_only(caplog, default_conf):
assert not default_conf['sell_profit_only'] assert not default_conf['sell_profit_only']
default_conf.update({ default_conf.update({
'strategy': 'StrategyTestV3', 'strategy': CURRENT_TEST_STRATEGY,
'sell_profit_only': True, 'sell_profit_only': True,
}) })
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)

View File

@ -7,6 +7,7 @@ import pytest
from freqtrade.commands import Arguments from freqtrade.commands import Arguments
from freqtrade.commands.cli_options import check_int_nonzero, check_int_positive from freqtrade.commands.cli_options import check_int_nonzero, check_int_positive
from tests.conftest import CURRENT_TEST_STRATEGY
# Parse common command-line-arguments. Used for all tools # Parse common command-line-arguments. Used for all tools
@ -123,7 +124,7 @@ def test_parse_args_backtesting_custom() -> None:
'-c', 'test_conf.json', '-c', 'test_conf.json',
'--ticker-interval', '1m', '--ticker-interval', '1m',
'--strategy-list', '--strategy-list',
'StrategyTestV2', CURRENT_TEST_STRATEGY,
'SampleStrategy' 'SampleStrategy'
] ]
call_args = Arguments(args).get_parsed_arg() call_args = Arguments(args).get_parsed_arg()

View File

@ -23,7 +23,8 @@ from freqtrade.constants import DEFAULT_DB_DRYRUN_URL, DEFAULT_DB_PROD_URL, ENV_
from freqtrade.enums import RunMode from freqtrade.enums import RunMode
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import OperationalException
from freqtrade.loggers import _set_loggers, setup_logging, setup_logging_pre from freqtrade.loggers import _set_loggers, setup_logging, setup_logging_pre
from tests.conftest import log_has, log_has_re, patched_configuration_load_config_file from tests.conftest import (CURRENT_TEST_STRATEGY, log_has, log_has_re,
patched_configuration_load_config_file)
@pytest.fixture(scope="function") @pytest.fixture(scope="function")
@ -403,7 +404,7 @@ def test_setup_configuration_without_arguments(mocker, default_conf, caplog) ->
arglist = [ arglist = [
'backtesting', 'backtesting',
'--config', 'config.json', '--config', 'config.json',
'--strategy', 'StrategyTestV2', '--strategy', CURRENT_TEST_STRATEGY,
] ]
args = Arguments(arglist).get_parsed_arg() args = Arguments(arglist).get_parsed_arg()
@ -440,7 +441,7 @@ def test_setup_configuration_with_arguments(mocker, default_conf, caplog) -> Non
arglist = [ arglist = [
'backtesting', 'backtesting',
'--config', 'config.json', '--config', 'config.json',
'--strategy', 'StrategyTestV2', '--strategy', CURRENT_TEST_STRATEGY,
'--datadir', '/foo/bar', '--datadir', '/foo/bar',
'--userdir', "/tmp/freqtrade", '--userdir', "/tmp/freqtrade",
'--ticker-interval', '1m', '--ticker-interval', '1m',
@ -497,7 +498,7 @@ def test_setup_configuration_with_stratlist(mocker, default_conf, caplog) -> Non
'--ticker-interval', '1m', '--ticker-interval', '1m',
'--export', 'trades', '--export', 'trades',
'--strategy-list', '--strategy-list',
'StrategyTestV2', CURRENT_TEST_STRATEGY,
'TestStrategy' 'TestStrategy'
] ]