Elffuss BraidHub

kikocis/freqtrade public

develop · 46.4 KiBRawPermalink
1# pragma pylint: disable=missing-docstring, protected-access, invalid-name
2import json
3import logging
4import sys
5import warnings
6from copy import deepcopy
7from pathlib import Path
8from unittest.mock import MagicMock
9
10import pytest
11from jsonschema import ValidationError
12
13from freqtrade.commands import Arguments
14from freqtrade.configuration import (Configuration, check_exchange, remove_credentials,
15 validate_config_consistency)
16from freqtrade.configuration.config_validation import validate_config_schema
17from freqtrade.configuration.deprecated_settings import (check_conflicting_settings,
18 process_deprecated_setting,
19 process_removed_setting,
20 process_temporary_deprecated_settings)
21from freqtrade.configuration.load_config import load_config_file, log_config_error_range
22from freqtrade.constants import DEFAULT_DB_DRYRUN_URL, DEFAULT_DB_PROD_URL
23from freqtrade.exceptions import OperationalException
24from freqtrade.loggers import _set_loggers, setup_logging, setup_logging_pre
25from freqtrade.state import RunMode
26from tests.conftest import log_has, log_has_re, patched_configuration_load_config_file
27
28
29@pytest.fixture(scope="function")
30def all_conf():
31 config_file = Path(__file__).parents[1] / "config_full.json.example"
32 conf = load_config_file(str(config_file))
33 return conf
34
35
36def test_load_config_missing_attributes(default_conf) -> None:
37 conf = deepcopy(default_conf)
38 conf.pop('exchange')
39
40 with pytest.raises(ValidationError, match=r".*'exchange' is a required property.*"):
41 validate_config_schema(conf)
42
43 conf = deepcopy(default_conf)
44 conf.pop('stake_currency')
45 conf['runmode'] = RunMode.DRY_RUN
46 with pytest.raises(ValidationError, match=r".*'stake_currency' is a required property.*"):
47 validate_config_schema(conf)
48
49
50def test_load_config_incorrect_stake_amount(default_conf) -> None:
51 default_conf['stake_amount'] = 'fake'
52
53 with pytest.raises(ValidationError, match=r".*'fake' does not match 'unlimited'.*"):
54 validate_config_schema(default_conf)
55
56
57def test_load_config_file(default_conf, mocker, caplog) -> None:
58 del default_conf['user_data_dir']
59 file_mock = mocker.patch('freqtrade.configuration.load_config.open', mocker.mock_open(
60 read_data=json.dumps(default_conf)
61 ))
62
63 validated_conf = load_config_file('somefile')
64 assert file_mock.call_count == 1
65 assert validated_conf.items() >= default_conf.items()
66
67
68def test_load_config_file_error(default_conf, mocker, caplog) -> None:
69 del default_conf['user_data_dir']
70 filedata = json.dumps(default_conf).replace(
71 '"stake_amount": 0.001,', '"stake_amount": .001,')
72 mocker.patch('freqtrade.configuration.load_config.open', mocker.mock_open(read_data=filedata))
73 mocker.patch.object(Path, "read_text", MagicMock(return_value=filedata))
74
75 with pytest.raises(OperationalException, match=r".*Please verify the following segment.*"):
76 load_config_file('somefile')
77
78
79def test_load_config_file_error_range(default_conf, mocker, caplog) -> None:
80 del default_conf['user_data_dir']
81 filedata = json.dumps(default_conf).replace(
82 '"stake_amount": 0.001,', '"stake_amount": .001,')
83 mocker.patch.object(Path, "read_text", MagicMock(return_value=filedata))
84
85 x = log_config_error_range('somefile', 'Parse error at offset 64: Invalid value.')
86 assert isinstance(x, str)
87 assert (x == '{"max_open_trades": 1, "stake_currency": "BTC", '
88 '"stake_amount": .001, "fiat_display_currency": "USD", '
89 '"timeframe": "5m", "dry_run": true, "cance')
90
91
92def test__args_to_config(caplog):
93
94 arg_list = ['trade', '--strategy-path', 'TestTest']
95 args = Arguments(arg_list).get_parsed_arg()
96 configuration = Configuration(args)
97 config = {}
98 with warnings.catch_warnings(record=True) as w:
99 warnings.simplefilter("always")
100 # No warnings ...
101 configuration._args_to_config(config, argname="strategy_path", logstring="DeadBeef")
102 assert len(w) == 0
103 assert log_has("DeadBeef", caplog)
104 assert config['strategy_path'] == "TestTest"
105
106 configuration = Configuration(args)
107 config = {}
108 with warnings.catch_warnings(record=True) as w:
109 warnings.simplefilter("always")
110 # Deprecation warnings!
111 configuration._args_to_config(config, argname="strategy_path", logstring="DeadBeef",
112 deprecated_msg="Going away soon!")
113 assert len(w) == 1
114 assert issubclass(w[-1].category, DeprecationWarning)
115 assert "DEPRECATED: Going away soon!" in str(w[-1].message)
116 assert log_has("DeadBeef", caplog)
117 assert config['strategy_path'] == "TestTest"
118
119
120def test_load_config_max_open_trades_zero(default_conf, mocker, caplog) -> None:
121 default_conf['max_open_trades'] = 0
122 patched_configuration_load_config_file(mocker, default_conf)
123
124 args = Arguments(['trade']).get_parsed_arg()
125 configuration = Configuration(args)
126 validated_conf = configuration.load_config()
127
128 assert validated_conf['max_open_trades'] == 0
129 assert 'internals' in validated_conf
130
131
132def test_load_config_combine_dicts(default_conf, mocker, caplog) -> None:
133 conf1 = deepcopy(default_conf)
134 conf2 = deepcopy(default_conf)
135 del conf1['exchange']['key']
136 del conf1['exchange']['secret']
137 del conf2['exchange']['name']
138 conf2['exchange']['pair_whitelist'] += ['NANO/BTC']
139
140 config_files = [conf1, conf2]
141
142 configsmock = MagicMock(side_effect=config_files)
143 mocker.patch(
144 'freqtrade.configuration.configuration.load_config_file',
145 configsmock
146 )
147
148 arg_list = ['trade', '-c', 'test_conf.json', '--config', 'test2_conf.json', ]
149 args = Arguments(arg_list).get_parsed_arg()
150 configuration = Configuration(args)
151 validated_conf = configuration.load_config()
152
153 exchange_conf = default_conf['exchange']
154 assert validated_conf['exchange']['name'] == exchange_conf['name']
155 assert validated_conf['exchange']['key'] == exchange_conf['key']
156 assert validated_conf['exchange']['secret'] == exchange_conf['secret']
157 assert validated_conf['exchange']['pair_whitelist'] != conf1['exchange']['pair_whitelist']
158 assert validated_conf['exchange']['pair_whitelist'] == conf2['exchange']['pair_whitelist']
159
160 assert 'internals' in validated_conf
161
162
163def test_from_config(default_conf, mocker, caplog) -> None:
164 conf1 = deepcopy(default_conf)
165 conf2 = deepcopy(default_conf)
166 del conf1['exchange']['key']
167 del conf1['exchange']['secret']
168 del conf2['exchange']['name']
169 conf2['exchange']['pair_whitelist'] += ['NANO/BTC']
170 conf2['fiat_display_currency'] = "EUR"
171 config_files = [conf1, conf2]
172 mocker.patch('freqtrade.configuration.configuration.create_datadir', lambda c, x: x)
173
174 configsmock = MagicMock(side_effect=config_files)
175 mocker.patch('freqtrade.configuration.configuration.load_config_file', configsmock)
176
177 validated_conf = Configuration.from_files(['test_conf.json', 'test2_conf.json'])
178
179 exchange_conf = default_conf['exchange']
180 assert validated_conf['exchange']['name'] == exchange_conf['name']
181 assert validated_conf['exchange']['key'] == exchange_conf['key']
182 assert validated_conf['exchange']['secret'] == exchange_conf['secret']
183 assert validated_conf['exchange']['pair_whitelist'] != conf1['exchange']['pair_whitelist']
184 assert validated_conf['exchange']['pair_whitelist'] == conf2['exchange']['pair_whitelist']
185 assert validated_conf['fiat_display_currency'] == "EUR"
186 assert 'internals' in validated_conf
187 assert isinstance(validated_conf['user_data_dir'], Path)
188
189
190def test_print_config(default_conf, mocker, caplog) -> None:
191 conf1 = deepcopy(default_conf)
192 # Delete non-json elements from default_conf
193 del conf1['user_data_dir']
194 config_files = [conf1]
195
196 configsmock = MagicMock(side_effect=config_files)
197 mocker.patch('freqtrade.configuration.configuration.create_datadir', lambda c, x: x)
198 mocker.patch('freqtrade.configuration.configuration.load_config_file', configsmock)
199
200 validated_conf = Configuration.from_files(['test_conf.json'])
201
202 assert isinstance(validated_conf['user_data_dir'], Path)
203 assert "user_data_dir" in validated_conf
204 assert "original_config" in validated_conf
205 assert isinstance(json.dumps(validated_conf['original_config']), str)
206
207
208def test_load_config_max_open_trades_minus_one(default_conf, mocker, caplog) -> None:
209 default_conf['max_open_trades'] = -1
210 patched_configuration_load_config_file(mocker, default_conf)
211
212 args = Arguments(['trade']).get_parsed_arg()
213 configuration = Configuration(args)
214 validated_conf = configuration.load_config()
215
216 assert validated_conf['max_open_trades'] > 999999999
217 assert validated_conf['max_open_trades'] == float('inf')
218 assert "runmode" in validated_conf
219 assert validated_conf['runmode'] == RunMode.DRY_RUN
220
221
222def test_load_config_file_exception(mocker) -> None:
223 mocker.patch(
224 'freqtrade.configuration.configuration.open',
225 MagicMock(side_effect=FileNotFoundError('File not found'))
226 )
227
228 with pytest.raises(OperationalException, match=r'.*Config file "somefile" not found!*'):
229 load_config_file('somefile')
230
231
232def test_load_config(default_conf, mocker) -> None:
233 del default_conf['strategy_path']
234 patched_configuration_load_config_file(mocker, default_conf)
235
236 args = Arguments(['trade']).get_parsed_arg()
237 configuration = Configuration(args)
238 validated_conf = configuration.load_config()
239
240 assert validated_conf.get('strategy_path') is None
241 assert 'edge' not in validated_conf
242
243
244def test_load_config_with_params(default_conf, mocker) -> None:
245 patched_configuration_load_config_file(mocker, default_conf)
246
247 arglist = [
248 'trade',
249 '--strategy', 'TestStrategy',
250 '--strategy-path', '/some/path',
251 '--db-url', 'sqlite:///someurl',
252 ]
253 args = Arguments(arglist).get_parsed_arg()
254 configuration = Configuration(args)
255 validated_conf = configuration.load_config()
256
257 assert validated_conf.get('strategy') == 'TestStrategy'
258 assert validated_conf.get('strategy_path') == '/some/path'
259 assert validated_conf.get('db_url') == 'sqlite:///someurl'
260
261 # Test conf provided db_url prod
262 conf = default_conf.copy()
263 conf["dry_run"] = False
264 conf["db_url"] = "sqlite:///path/to/db.sqlite"
265 patched_configuration_load_config_file(mocker, conf)
266
267 arglist = [
268 'trade',
269 '--strategy', 'TestStrategy',
270 '--strategy-path', '/some/path'
271 ]
272 args = Arguments(arglist).get_parsed_arg()
273
274 configuration = Configuration(args)
275 validated_conf = configuration.load_config()
276 assert validated_conf.get('db_url') == "sqlite:///path/to/db.sqlite"
277
278 # Test conf provided db_url dry_run
279 conf = default_conf.copy()
280 conf["dry_run"] = True
281 conf["db_url"] = "sqlite:///path/to/db.sqlite"
282 patched_configuration_load_config_file(mocker, conf)
283
284 arglist = [
285 'trade',
286 '--strategy', 'TestStrategy',
287 '--strategy-path', '/some/path'
288 ]
289 args = Arguments(arglist).get_parsed_arg()
290
291 configuration = Configuration(args)
292 validated_conf = configuration.load_config()
293 assert validated_conf.get('db_url') == "sqlite:///path/to/db.sqlite"
294
295 # Test args provided db_url prod
296 conf = default_conf.copy()
297 conf["dry_run"] = False
298 del conf["db_url"]
299 patched_configuration_load_config_file(mocker, conf)
300
301 arglist = [
302 'trade',
303 '--strategy', 'TestStrategy',
304 '--strategy-path', '/some/path'
305 ]
306 args = Arguments(arglist).get_parsed_arg()
307
308 configuration = Configuration(args)
309 validated_conf = configuration.load_config()
310 assert validated_conf.get('db_url') == DEFAULT_DB_PROD_URL
311 assert "runmode" in validated_conf
312 assert validated_conf['runmode'] == RunMode.LIVE
313
314 # Test args provided db_url dry_run
315 conf = default_conf.copy()
316 conf["dry_run"] = True
317 conf["db_url"] = DEFAULT_DB_PROD_URL
318 patched_configuration_load_config_file(mocker, conf)
319
320 arglist = [
321 'trade',
322 '--strategy', 'TestStrategy',
323 '--strategy-path', '/some/path'
324 ]
325 args = Arguments(arglist).get_parsed_arg()
326
327 configuration = Configuration(args)
328 validated_conf = configuration.load_config()
329 assert validated_conf.get('db_url') == DEFAULT_DB_DRYRUN_URL
330
331
332@pytest.mark.parametrize("config_value,expected,arglist", [
333 (True, True, ['trade', '--dry-run']), # Leave config untouched
334 (False, True, ['trade', '--dry-run']), # Override config untouched
335 (False, False, ['trade']), # Leave config untouched
336 (True, True, ['trade']), # Leave config untouched
337])
338def test_load_dry_run(default_conf, mocker, config_value, expected, arglist) -> None:
339
340 default_conf['dry_run'] = config_value
341 patched_configuration_load_config_file(mocker, default_conf)
342
343 configuration = Configuration(Arguments(arglist).get_parsed_arg())
344 validated_conf = configuration.load_config()
345
346 assert validated_conf['dry_run'] is expected
347 assert validated_conf['runmode'] == (RunMode.DRY_RUN if expected else RunMode.LIVE)
348
349
350def test_load_custom_strategy(default_conf, mocker) -> None:
351 default_conf.update({
352 'strategy': 'CustomStrategy',
353 'strategy_path': '/tmp/strategies',
354 })
355 patched_configuration_load_config_file(mocker, default_conf)
356
357 args = Arguments(['trade']).get_parsed_arg()
358 configuration = Configuration(args)
359 validated_conf = configuration.load_config()
360
361 assert validated_conf.get('strategy') == 'CustomStrategy'
362 assert validated_conf.get('strategy_path') == '/tmp/strategies'
363
364
365def test_show_info(default_conf, mocker, caplog) -> None:
366 patched_configuration_load_config_file(mocker, default_conf)
367
368 arglist = [
369 'trade',
370 '--strategy', 'TestStrategy',
371 '--db-url', 'sqlite:///tmp/testdb',
372 ]
373 args = Arguments(arglist).get_parsed_arg()
374
375 configuration = Configuration(args)
376 configuration.get_config()
377
378 assert log_has('Using DB: "sqlite:///tmp/testdb"', caplog)
379 assert log_has('Dry run is enabled', caplog)
380
381
382def test_setup_configuration_without_arguments(mocker, default_conf, caplog) -> None:
383 patched_configuration_load_config_file(mocker, default_conf)
384
385 arglist = [
386 'backtesting',
387 '--config', 'config.json',
388 '--strategy', 'DefaultStrategy',
389 ]
390
391 args = Arguments(arglist).get_parsed_arg()
392
393 configuration = Configuration(args)
394 config = configuration.get_config()
395 assert 'max_open_trades' in config
396 assert 'stake_currency' in config
397 assert 'stake_amount' in config
398 assert 'exchange' in config
399 assert 'pair_whitelist' in config['exchange']
400 assert 'datadir' in config
401 assert 'user_data_dir' in config
402 assert log_has('Using data directory: {} ...'.format(config['datadir']), caplog)
403 assert 'timeframe' in config
404 assert not log_has('Parameter -i/--timeframe detected ...', caplog)
405
406 assert 'position_stacking' not in config
407 assert not log_has('Parameter --enable-position-stacking detected ...', caplog)
408
409 assert 'timerange' not in config
410 assert 'export' not in config
411
412
413def test_setup_configuration_with_arguments(mocker, default_conf, caplog) -> None:
414 patched_configuration_load_config_file(mocker, default_conf)
415 mocker.patch(
416 'freqtrade.configuration.configuration.create_datadir',
417 lambda c, x: x
418 )
419 mocker.patch(
420 'freqtrade.configuration.configuration.create_userdata_dir',
421 lambda x, *args, **kwargs: Path(x)
422 )
423 arglist = [
424 'backtesting',
425 '--config', 'config.json',
426 '--strategy', 'DefaultStrategy',
427 '--datadir', '/foo/bar',
428 '--userdir', "/tmp/freqtrade",
429 '--ticker-interval', '1m',
430 '--enable-position-stacking',
431 '--disable-max-market-positions',
432 '--timerange', ':100',
433 '--export', '/bar/foo',
434 '--stake-amount', 'unlimited'
435 ]
436
437 args = Arguments(arglist).get_parsed_arg()
438
439 configuration = Configuration(args)
440 config = configuration.get_config()
441 assert 'max_open_trades' in config
442 assert 'stake_currency' in config
443 assert 'stake_amount' in config
444 assert 'exchange' in config
445 assert 'pair_whitelist' in config['exchange']
446 assert 'datadir' in config
447 assert log_has('Using data directory: {} ...'.format("/foo/bar"), caplog)
448 assert log_has('Using user-data directory: {} ...'.format(Path("/tmp/freqtrade")), caplog)
449 assert 'user_data_dir' in config
450
451 assert 'timeframe' in config
452 assert log_has('Parameter -i/--timeframe detected ... Using timeframe: 1m ...',
453 caplog)
454
455 assert 'position_stacking' in config
456 assert log_has('Parameter --enable-position-stacking detected ...', caplog)
457
458 assert 'use_max_market_positions' in config
459 assert log_has('Parameter --disable-max-market-positions detected ...', caplog)
460 assert log_has('max_open_trades set to unlimited ...', caplog)
461
462 assert 'timerange' in config
463 assert log_has('Parameter --timerange detected: {} ...'.format(config['timerange']), caplog)
464
465 assert 'export' in config
466 assert log_has('Parameter --export detected: {} ...'.format(config['export']), caplog)
467 assert 'stake_amount' in config
468 assert config['stake_amount'] == 'unlimited'
469
470
471def test_setup_configuration_with_stratlist(mocker, default_conf, caplog) -> None:
472 """
473 Test setup_configuration() function
474 """
475 patched_configuration_load_config_file(mocker, default_conf)
476
477 arglist = [
478 'backtesting',
479 '--config', 'config.json',
480 '--ticker-interval', '1m',
481 '--export', '/bar/foo',
482 '--strategy-list',
483 'DefaultStrategy',
484 'TestStrategy'
485 ]
486
487 args = Arguments(arglist).get_parsed_arg()
488
489 configuration = Configuration(args, RunMode.BACKTEST)
490 config = configuration.get_config()
491 assert config['runmode'] == RunMode.BACKTEST
492 assert 'max_open_trades' in config
493 assert 'stake_currency' in config
494 assert 'stake_amount' in config
495 assert 'exchange' in config
496 assert 'pair_whitelist' in config['exchange']
497 assert 'datadir' in config
498 assert log_has('Using data directory: {} ...'.format(config['datadir']), caplog)
499 assert 'timeframe' in config
500 assert log_has('Parameter -i/--timeframe detected ... Using timeframe: 1m ...',
501 caplog)
502
503 assert 'strategy_list' in config
504 assert log_has('Using strategy list of 2 strategies', caplog)
505
506 assert 'position_stacking' not in config
507
508 assert 'use_max_market_positions' not in config
509
510 assert 'timerange' not in config
511
512 assert 'export' in config
513 assert log_has('Parameter --export detected: {} ...'.format(config['export']), caplog)
514
515
516def test_hyperopt_with_arguments(mocker, default_conf, caplog) -> None:
517 patched_configuration_load_config_file(mocker, default_conf)
518
519 arglist = [
520 'hyperopt',
521 '--epochs', '10',
522 '--spaces', 'all',
523 ]
524 args = Arguments(arglist).get_parsed_arg()
525
526 configuration = Configuration(args, RunMode.HYPEROPT)
527 config = configuration.get_config()
528
529 assert 'epochs' in config
530 assert int(config['epochs']) == 10
531 assert log_has('Parameter --epochs detected ... Will run Hyperopt with for 10 epochs ...',
532 caplog)
533
534 assert 'spaces' in config
535 assert config['spaces'] == ['all']
536 assert log_has("Parameter -s/--spaces detected: ['all']", caplog)
537 assert "runmode" in config
538 assert config['runmode'] == RunMode.HYPEROPT
539
540
541def test_check_exchange(default_conf, caplog) -> None:
542 # Test an officially supported by Freqtrade team exchange
543 default_conf['runmode'] = RunMode.DRY_RUN
544 default_conf.get('exchange').update({'name': 'BITTREX'})
545 assert check_exchange(default_conf)
546 assert log_has_re(r"Exchange .* is officially supported by the Freqtrade development team\.",
547 caplog)
548 caplog.clear()
549
550 # Test an officially supported by Freqtrade team exchange
551 default_conf.get('exchange').update({'name': 'binance'})
552 assert check_exchange(default_conf)
553 assert log_has_re(r"Exchange .* is officially supported by the Freqtrade development team\.",
554 caplog)
555 caplog.clear()
556
557 # Test an available exchange, supported by ccxt
558 default_conf.get('exchange').update({'name': 'huobipro'})
559 assert check_exchange(default_conf)
560 assert log_has_re(r"Exchange .* is known to the the ccxt library, available for the bot, "
561 r"but not officially supported "
562 r"by the Freqtrade development team\. .*", caplog)
563 caplog.clear()
564
565 # Test a 'bad' exchange, which known to have serious problems
566 default_conf.get('exchange').update({'name': 'bitmex'})
567 with pytest.raises(OperationalException,
568 match=r"Exchange .* will not work with Freqtrade\..*"):
569 check_exchange(default_conf)
570 caplog.clear()
571
572 # Test a 'bad' exchange with check_for_bad=False
573 default_conf.get('exchange').update({'name': 'bitmex'})
574 assert check_exchange(default_conf, False)
575 assert log_has_re(r"Exchange .* is known to the the ccxt library, available for the bot, "
576 r"but not officially supported "
577 r"by the Freqtrade development team\. .*", caplog)
578 caplog.clear()
579
580 # Test an invalid exchange
581 default_conf.get('exchange').update({'name': 'unknown_exchange'})
582 with pytest.raises(
583 OperationalException,
584 match=r'Exchange "unknown_exchange" is not known to the ccxt library '
585 r'and therefore not available for the bot.*'
586 ):
587 check_exchange(default_conf)
588
589 # Test no exchange...
590 default_conf.get('exchange').update({'name': ''})
591 default_conf['runmode'] = RunMode.PLOT
592 assert check_exchange(default_conf)
593
594 # Test no exchange...
595 default_conf.get('exchange').update({'name': ''})
596 default_conf['runmode'] = RunMode.UTIL_EXCHANGE
597 with pytest.raises(OperationalException,
598 match=r'This command requires a configured exchange.*'):
599 check_exchange(default_conf)
600
601
602def test_remove_credentials(default_conf, caplog) -> None:
603 conf = deepcopy(default_conf)
604 conf['dry_run'] = False
605 remove_credentials(conf)
606
607 assert conf['dry_run'] is True
608 assert conf['exchange']['key'] == ''
609 assert conf['exchange']['secret'] == ''
610 assert conf['exchange']['password'] == ''
611 assert conf['exchange']['uid'] == ''
612
613
614def test_cli_verbose_with_params(default_conf, mocker, caplog) -> None:
615 patched_configuration_load_config_file(mocker, default_conf)
616
617 # Prevent setting loggers
618 mocker.patch('freqtrade.loggers._set_loggers', MagicMock)
619 arglist = ['trade', '-vvv']
620 args = Arguments(arglist).get_parsed_arg()
621
622 configuration = Configuration(args)
623 validated_conf = configuration.load_config()
624
625 assert validated_conf.get('verbosity') == 3
626 assert log_has('Verbosity set to 3', caplog)
627
628
629def test_set_loggers() -> None:
630 # Reset Logging to Debug, otherwise this fails randomly as it's set globally
631 logging.getLogger('requests').setLevel(logging.DEBUG)
632 logging.getLogger("urllib3").setLevel(logging.DEBUG)
633 logging.getLogger('ccxt.base.exchange').setLevel(logging.DEBUG)
634 logging.getLogger('telegram').setLevel(logging.DEBUG)
635
636 previous_value1 = logging.getLogger('requests').level
637 previous_value2 = logging.getLogger('ccxt.base.exchange').level
638 previous_value3 = logging.getLogger('telegram').level
639
640 _set_loggers()
641
642 value1 = logging.getLogger('requests').level
643 assert previous_value1 is not value1
644 assert value1 is logging.INFO
645
646 value2 = logging.getLogger('ccxt.base.exchange').level
647 assert previous_value2 is not value2
648 assert value2 is logging.INFO
649
650 value3 = logging.getLogger('telegram').level
651 assert previous_value3 is not value3
652 assert value3 is logging.INFO
653
654 _set_loggers(verbosity=2)
655
656 assert logging.getLogger('requests').level is logging.DEBUG
657 assert logging.getLogger('ccxt.base.exchange').level is logging.INFO
658 assert logging.getLogger('telegram').level is logging.INFO
659 assert logging.getLogger('werkzeug').level is logging.INFO
660
661 _set_loggers(verbosity=3, api_verbosity='error')
662
663 assert logging.getLogger('requests').level is logging.DEBUG
664 assert logging.getLogger('ccxt.base.exchange').level is logging.DEBUG
665 assert logging.getLogger('telegram').level is logging.INFO
666 assert logging.getLogger('werkzeug').level is logging.ERROR
667
668
669@pytest.mark.skipif(sys.platform == "win32", reason="does not run on windows")
670def test_set_loggers_syslog():
671 logger = logging.getLogger()
672 orig_handlers = logger.handlers
673 logger.handlers = []
674
675 config = {'verbosity': 2,
676 'logfile': 'syslog:/dev/log',
677 }
678
679 setup_logging_pre()
680 setup_logging(config)
681 assert len(logger.handlers) == 3
682 assert [x for x in logger.handlers if type(x) == logging.handlers.SysLogHandler]
683 assert [x for x in logger.handlers if type(x) == logging.StreamHandler]
684 assert [x for x in logger.handlers if type(x) == logging.handlers.BufferingHandler]
685 # setting up logging again should NOT cause the loggers to be added a second time.
686 setup_logging(config)
687 assert len(logger.handlers) == 3
688 # reset handlers to not break pytest
689 logger.handlers = orig_handlers
690
691
692@pytest.mark.skipif(sys.platform == "win32", reason="does not run on windows")
693def test_set_loggers_Filehandler(tmpdir):
694 logger = logging.getLogger()
695 orig_handlers = logger.handlers
696 logger.handlers = []
697 logfile = Path(tmpdir) / 'ft_logfile.log'
698 config = {'verbosity': 2,
699 'logfile': str(logfile),
700 }
701
702 setup_logging_pre()
703 setup_logging(config)
704 assert len(logger.handlers) == 3
705 assert [x for x in logger.handlers if type(x) == logging.handlers.RotatingFileHandler]
706 assert [x for x in logger.handlers if type(x) == logging.StreamHandler]
707 assert [x for x in logger.handlers if type(x) == logging.handlers.BufferingHandler]
708 # setting up logging again should NOT cause the loggers to be added a second time.
709 setup_logging(config)
710 assert len(logger.handlers) == 3
711 # reset handlers to not break pytest
712 if logfile.exists:
713 logfile.unlink()
714 logger.handlers = orig_handlers
715
716
717@pytest.mark.skip(reason="systemd is not installed on every system, so we're not testing this.")
718def test_set_loggers_journald(mocker):
719 logger = logging.getLogger()
720 orig_handlers = logger.handlers
721 logger.handlers = []
722
723 config = {'verbosity': 2,
724 'logfile': 'journald',
725 }
726
727 setup_logging(config)
728 assert len(logger.handlers) == 2
729 assert [x for x in logger.handlers if type(x).__name__ == "JournaldLogHandler"]
730 assert [x for x in logger.handlers if type(x) == logging.StreamHandler]
731 # reset handlers to not break pytest
732 logger.handlers = orig_handlers
733
734
735def test_set_loggers_journald_importerror(mocker, import_fails):
736 logger = logging.getLogger()
737 orig_handlers = logger.handlers
738 logger.handlers = []
739
740 config = {'verbosity': 2,
741 'logfile': 'journald',
742 }
743 with pytest.raises(OperationalException,
744 match=r'You need the systemd python package.*'):
745 setup_logging(config)
746 logger.handlers = orig_handlers
747
748
749def test_set_logfile(default_conf, mocker, tmpdir):
750 patched_configuration_load_config_file(mocker, default_conf)
751 f = Path(tmpdir / "test_file.log")
752 assert not f.is_file()
753 arglist = [
754 'trade', '--logfile', str(f),
755 ]
756 args = Arguments(arglist).get_parsed_arg()
757 configuration = Configuration(args)
758 validated_conf = configuration.load_config()
759
760 assert validated_conf['logfile'] == str(f)
761 assert f.is_file()
762 try:
763 f.unlink()
764 except Exception:
765 pass
766
767
768def test_load_config_warn_forcebuy(default_conf, mocker, caplog) -> None:
769 default_conf['forcebuy_enable'] = True
770 patched_configuration_load_config_file(mocker, default_conf)
771
772 args = Arguments(['trade']).get_parsed_arg()
773 configuration = Configuration(args)
774 validated_conf = configuration.load_config()
775
776 assert validated_conf.get('forcebuy_enable')
777 assert log_has('`forcebuy` RPC message enabled.', caplog)
778
779
780def test_validate_default_conf(default_conf) -> None:
781 # Validate via our validator - we allow setting defaults!
782 validate_config_schema(default_conf)
783
784
785def test_validate_max_open_trades(default_conf):
786 default_conf['max_open_trades'] = float('inf')
787 default_conf['stake_amount'] = 'unlimited'
788 with pytest.raises(OperationalException, match='`max_open_trades` and `stake_amount` '
789 'cannot both be unlimited.'):
790 validate_config_consistency(default_conf)
791
792
793def test_validate_price_side(default_conf):
794 default_conf['order_types'] = {
795 "buy": "limit",
796 "sell": "limit",
797 "stoploss": "limit",
798 "stoploss_on_exchange": False,
799 }
800 # Default should pass
801 validate_config_consistency(default_conf)
802
803 conf = deepcopy(default_conf)
804 conf['order_types']['buy'] = 'market'
805 with pytest.raises(OperationalException,
806 match='Market buy orders require bid_strategy.price_side = "ask".'):
807 validate_config_consistency(conf)
808
809 conf = deepcopy(default_conf)
810 conf['order_types']['sell'] = 'market'
811 with pytest.raises(OperationalException,
812 match='Market sell orders require ask_strategy.price_side = "bid".'):
813 validate_config_consistency(conf)
814
815 # Validate inversed case
816 conf = deepcopy(default_conf)
817 conf['order_types']['sell'] = 'market'
818 conf['order_types']['buy'] = 'market'
819 conf['ask_strategy']['price_side'] = 'bid'
820 conf['bid_strategy']['price_side'] = 'ask'
821
822 validate_config_consistency(conf)
823
824
825def test_validate_tsl(default_conf):
826 default_conf['stoploss'] = 0.0
827 with pytest.raises(OperationalException, match='The config stoploss needs to be different '
828 'from 0 to avoid problems with sell orders.'):
829 validate_config_consistency(default_conf)
830 default_conf['stoploss'] = -0.10
831
832 default_conf['trailing_stop'] = True
833 default_conf['trailing_stop_positive'] = 0
834 default_conf['trailing_stop_positive_offset'] = 0
835
836 default_conf['trailing_only_offset_is_reached'] = True
837 with pytest.raises(OperationalException,
838 match=r'The config trailing_only_offset_is_reached needs '
839 'trailing_stop_positive_offset to be more than 0 in your config.'):
840 validate_config_consistency(default_conf)
841
842 default_conf['trailing_stop_positive_offset'] = 0.01
843 default_conf['trailing_stop_positive'] = 0.015
844 with pytest.raises(OperationalException,
845 match=r'The config trailing_stop_positive_offset needs '
846 'to be greater than trailing_stop_positive in your config.'):
847 validate_config_consistency(default_conf)
848
849 default_conf['trailing_stop_positive'] = 0.01
850 default_conf['trailing_stop_positive_offset'] = 0.015
851 validate_config_consistency(default_conf)
852
853 # 0 trailing stop positive - results in "Order would trigger immediately"
854 default_conf['trailing_stop_positive'] = 0
855 default_conf['trailing_stop_positive_offset'] = 0.02
856 default_conf['trailing_only_offset_is_reached'] = False
857 with pytest.raises(OperationalException,
858 match='The config trailing_stop_positive needs to be different from 0 '
859 'to avoid problems with sell orders'):
860 validate_config_consistency(default_conf)
861
862
863def test_validate_edge2(edge_conf):
864 edge_conf.update({"ask_strategy": {
865 "use_sell_signal": True,
866 }})
867 # Passes test
868 validate_config_consistency(edge_conf)
869
870 edge_conf.update({"ask_strategy": {
871 "use_sell_signal": False,
872 }})
873 with pytest.raises(OperationalException, match="Edge requires `use_sell_signal` to be True, "
874 "otherwise no sells will happen."):
875 validate_config_consistency(edge_conf)
876
877
878def test_validate_whitelist(default_conf):
879 default_conf['runmode'] = RunMode.DRY_RUN
880 # Test regular case - has whitelist and uses StaticPairlist
881 validate_config_consistency(default_conf)
882 conf = deepcopy(default_conf)
883 del conf['exchange']['pair_whitelist']
884 # Test error case
885 with pytest.raises(OperationalException,
886 match="StaticPairList requires pair_whitelist to be set."):
887
888 validate_config_consistency(conf)
889
890 conf = deepcopy(default_conf)
891
892 conf.update({"pairlists": [{
893 "method": "VolumePairList",
894 }]})
895 # Dynamic whitelist should not care about pair_whitelist
896 validate_config_consistency(conf)
897 del conf['exchange']['pair_whitelist']
898
899 validate_config_consistency(conf)
900
901
902@pytest.mark.parametrize('protconf,expected', [
903 ([], None),
904 ([{"method": "StoplossGuard", "lookback_period": 2000, "stop_duration_candles": 10}], None),
905 ([{"method": "StoplossGuard", "lookback_period_candles": 20, "stop_duration": 10}], None),
906 ([{"method": "StoplossGuard", "lookback_period_candles": 20, "lookback_period": 2000,
907 "stop_duration": 10}], r'Protections must specify either `lookback_period`.*'),
908 ([{"method": "StoplossGuard", "lookback_period": 20, "stop_duration": 10,
909 "stop_duration_candles": 10}], r'Protections must specify either `stop_duration`.*'),
910])
911def test_validate_protections(default_conf, protconf, expected):
912 conf = deepcopy(default_conf)
913 conf['protections'] = protconf
914 if expected:
915 with pytest.raises(OperationalException, match=expected):
916 validate_config_consistency(conf)
917 else:
918 validate_config_consistency(conf)
919
920
921def test_load_config_test_comments() -> None:
922 """
923 Load config with comments
924 """
925 config_file = Path(__file__).parents[0] / "config_test_comments.json"
926 conf = load_config_file(str(config_file))
927
928 assert conf
929
930
931def test_load_config_default_exchange(all_conf) -> None:
932 """
933 config['exchange'] subtree has required options in it
934 so it cannot be omitted in the config
935 """
936 del all_conf['exchange']
937
938 assert 'exchange' not in all_conf
939
940 with pytest.raises(ValidationError,
941 match=r"'exchange' is a required property"):
942 validate_config_schema(all_conf)
943
944
945def test_load_config_default_exchange_name(all_conf) -> None:
946 """
947 config['exchange']['name'] option is required
948 so it cannot be omitted in the config
949 """
950 del all_conf['exchange']['name']
951
952 assert 'name' not in all_conf['exchange']
953
954 with pytest.raises(ValidationError,
955 match=r"'name' is a required property"):
956 validate_config_schema(all_conf)
957
958
959def test_load_config_stoploss_exchange_limit_ratio(all_conf) -> None:
960 all_conf['order_types']['stoploss_on_exchange_limit_ratio'] = 1.15
961
962 with pytest.raises(ValidationError,
963 match=r"1.15 is greater than the maximum"):
964 validate_config_schema(all_conf)
965
966
967@pytest.mark.parametrize("keys", [("exchange", "sandbox", False),
968 ("exchange", "key", ""),
969 ("exchange", "secret", ""),
970 ("exchange", "password", ""),
971 ])
972def test_load_config_default_subkeys(all_conf, keys) -> None:
973 """
974 Test for parameters with default values in sub-paths
975 so they can be omitted in the config and the default value
976 should is added to the config.
977 """
978 # Get first level key
979 key = keys[0]
980 # get second level key
981 subkey = keys[1]
982
983 del all_conf[key][subkey]
984
985 assert subkey not in all_conf[key]
986
987 validate_config_schema(all_conf)
988 assert subkey in all_conf[key]
989 assert all_conf[key][subkey] == keys[2]
990
991
992def test_pairlist_resolving():
993 arglist = [
994 'download-data',
995 '--pairs', 'ETH/BTC', 'XRP/BTC',
996 '--exchange', 'binance'
997 ]
998
999 args = Arguments(arglist).get_parsed_arg()
1000
1001 configuration = Configuration(args, RunMode.OTHER)
1002 config = configuration.get_config()
1003
1004 assert config['pairs'] == ['ETH/BTC', 'XRP/BTC']
1005 assert config['exchange']['pair_whitelist'] == ['ETH/BTC', 'XRP/BTC']
1006 assert config['exchange']['name'] == 'binance'
1007
1008
1009def test_pairlist_resolving_with_config(mocker, default_conf):
1010 patched_configuration_load_config_file(mocker, default_conf)
1011 arglist = [
1012 'download-data',
1013 '--config', 'config.json',
1014 ]
1015
1016 args = Arguments(arglist).get_parsed_arg()
1017
1018 configuration = Configuration(args)
1019 config = configuration.get_config()
1020
1021 assert config['pairs'] == default_conf['exchange']['pair_whitelist']
1022 assert config['exchange']['name'] == default_conf['exchange']['name']
1023
1024 # Override pairs
1025 arglist = [
1026 'download-data',
1027 '--config', 'config.json',
1028 '--pairs', 'ETH/BTC', 'XRP/BTC',
1029 ]
1030
1031 args = Arguments(arglist).get_parsed_arg()
1032
1033 configuration = Configuration(args)
1034 config = configuration.get_config()
1035
1036 assert config['pairs'] == ['ETH/BTC', 'XRP/BTC']
1037 assert config['exchange']['name'] == default_conf['exchange']['name']
1038
1039
1040def test_pairlist_resolving_with_config_pl(mocker, default_conf):
1041 patched_configuration_load_config_file(mocker, default_conf)
1042
1043 arglist = [
1044 'download-data',
1045 '--config', 'config.json',
1046 '--pairs-file', 'tests/testdata/pairs.json',
1047 ]
1048
1049 args = Arguments(arglist).get_parsed_arg()
1050
1051 configuration = Configuration(args)
1052 config = configuration.get_config()
1053 assert len(config['pairs']) == 23
1054 assert 'ETH/BTC' in config['pairs']
1055 assert 'XRP/BTC' in config['pairs']
1056 assert config['exchange']['name'] == default_conf['exchange']['name']
1057
1058
1059def test_pairlist_resolving_with_config_pl_not_exists(mocker, default_conf):
1060 patched_configuration_load_config_file(mocker, default_conf)
1061
1062 arglist = [
1063 'download-data',
1064 '--config', 'config.json',
1065 '--pairs-file', 'tests/testdata/pairs_doesnotexist.json',
1066 ]
1067
1068 args = Arguments(arglist).get_parsed_arg()
1069
1070 with pytest.raises(OperationalException, match=r"No pairs file found with path.*"):
1071 configuration = Configuration(args)
1072 configuration.get_config()
1073
1074
1075def test_pairlist_resolving_fallback(mocker):
1076 mocker.patch.object(Path, "exists", MagicMock(return_value=True))
1077 mocker.patch.object(Path, "open", MagicMock(return_value=MagicMock()))
1078 mocker.patch("freqtrade.configuration.configuration.load_file",
1079 MagicMock(return_value=['XRP/BTC', 'ETH/BTC']))
1080 arglist = [
1081 'download-data',
1082 '--exchange', 'binance'
1083 ]
1084
1085 args = Arguments(arglist).get_parsed_arg()
1086 # Fix flaky tests if config.json exists
1087 args['config'] = None
1088
1089 configuration = Configuration(args, RunMode.OTHER)
1090 config = configuration.get_config()
1091
1092 assert config['pairs'] == ['ETH/BTC', 'XRP/BTC']
1093 assert config['exchange']['name'] == 'binance'
1094 assert config['datadir'] == Path.cwd() / "user_data/data/binance"
1095
1096
1097@pytest.mark.skip(reason='Currently no deprecated / moved sections')
1098# The below is kept as a sample for the future.
1099@pytest.mark.parametrize("setting", [
1100 ("ask_strategy", "use_sell_signal", True,
1101 "experimental", "use_sell_signal", False),
1102 ])
1103def test_process_temporary_deprecated_settings(mocker, default_conf, setting, caplog):
1104 patched_configuration_load_config_file(mocker, default_conf)
1105
1106 # Create sections for new and deprecated settings
1107 # (they may not exist in the config)
1108 default_conf[setting[0]] = {}
1109 default_conf[setting[3]] = {}
1110 # Assign new setting
1111 default_conf[setting[0]][setting[1]] = setting[2]
1112 # Assign deprecated setting
1113 default_conf[setting[3]][setting[4]] = setting[5]
1114
1115 # New and deprecated settings are conflicting ones
1116 with pytest.raises(OperationalException, match=r'DEPRECATED'):
1117 process_temporary_deprecated_settings(default_conf)
1118
1119 caplog.clear()
1120
1121 # Delete new setting
1122 del default_conf[setting[0]][setting[1]]
1123
1124 process_temporary_deprecated_settings(default_conf)
1125 assert log_has_re('DEPRECATED', caplog)
1126 # The value of the new setting shall have been set to the
1127 # value of the deprecated one
1128 assert default_conf[setting[0]][setting[1]] == setting[5]
1129
1130
1131@pytest.mark.parametrize("setting", [
1132 ("experimental", "use_sell_signal", False),
1133 ("experimental", "sell_profit_only", True),
1134 ("experimental", "ignore_roi_if_buy_signal", True),
1135 ])
1136def test_process_removed_settings(mocker, default_conf, setting):
1137 patched_configuration_load_config_file(mocker, default_conf)
1138
1139 # Create sections for new and deprecated settings
1140 # (they may not exist in the config)
1141 default_conf[setting[0]] = {}
1142 # Assign removed setting
1143 default_conf[setting[0]][setting[1]] = setting[2]
1144
1145 # New and deprecated settings are conflicting ones
1146 with pytest.raises(OperationalException,
1147 match=r'Setting .* has been moved'):
1148 process_temporary_deprecated_settings(default_conf)
1149
1150
1151def test_process_deprecated_setting_edge(mocker, edge_conf):
1152 patched_configuration_load_config_file(mocker, edge_conf)
1153 edge_conf.update({'edge': {
1154 'enabled': True,
1155 'capital_available_percentage': 0.5,
1156 }})
1157
1158 with pytest.raises(OperationalException,
1159 match=r"DEPRECATED.*Using 'edge.capital_available_percentage'*"):
1160 process_temporary_deprecated_settings(edge_conf)
1161
1162
1163def test_check_conflicting_settings(mocker, default_conf, caplog):
1164 patched_configuration_load_config_file(mocker, default_conf)
1165
1166 # Create sections for new and deprecated settings
1167 # (they may not exist in the config)
1168 default_conf['sectionA'] = {}
1169 default_conf['sectionB'] = {}
1170 # Assign new setting
1171 default_conf['sectionA']['new_setting'] = 'valA'
1172 # Assign deprecated setting
1173 default_conf['sectionB']['deprecated_setting'] = 'valB'
1174
1175 # New and deprecated settings are conflicting ones
1176 with pytest.raises(OperationalException, match=r'DEPRECATED'):
1177 check_conflicting_settings(default_conf,
1178 'sectionA', 'new_setting',
1179 'sectionB', 'deprecated_setting')
1180
1181 caplog.clear()
1182
1183 # Delete new setting (deprecated exists)
1184 del default_conf['sectionA']['new_setting']
1185 check_conflicting_settings(default_conf,
1186 'sectionA', 'new_setting',
1187 'sectionB', 'deprecated_setting')
1188 assert not log_has_re('DEPRECATED', caplog)
1189 assert 'new_setting' not in default_conf['sectionA']
1190
1191 caplog.clear()
1192
1193 # Assign new setting
1194 default_conf['sectionA']['new_setting'] = 'valA'
1195 # Delete deprecated setting
1196 del default_conf['sectionB']['deprecated_setting']
1197 check_conflicting_settings(default_conf,
1198 'sectionA', 'new_setting',
1199 'sectionB', 'deprecated_setting')
1200 assert not log_has_re('DEPRECATED', caplog)
1201 assert default_conf['sectionA']['new_setting'] == 'valA'
1202
1203
1204def test_process_deprecated_setting(mocker, default_conf, caplog):
1205 patched_configuration_load_config_file(mocker, default_conf)
1206
1207 # Create sections for new and deprecated settings
1208 # (they may not exist in the config)
1209 default_conf['sectionA'] = {}
1210 default_conf['sectionB'] = {}
1211 # Assign new setting
1212 default_conf['sectionA']['new_setting'] = 'valA'
1213 # Assign deprecated setting
1214 default_conf['sectionB']['deprecated_setting'] = 'valB'
1215
1216 # Both new and deprecated settings exists
1217 process_deprecated_setting(default_conf,
1218 'sectionA', 'new_setting',
1219 'sectionB', 'deprecated_setting')
1220 assert log_has_re('DEPRECATED', caplog)
1221 # The value of the new setting shall have been set to the
1222 # value of the deprecated one
1223 assert default_conf['sectionA']['new_setting'] == 'valB'
1224
1225 caplog.clear()
1226
1227 # Delete new setting (deprecated exists)
1228 del default_conf['sectionA']['new_setting']
1229 process_deprecated_setting(default_conf,
1230 'sectionA', 'new_setting',
1231 'sectionB', 'deprecated_setting')
1232 assert log_has_re('DEPRECATED', caplog)
1233 # The value of the new setting shall have been set to the
1234 # value of the deprecated one
1235 assert default_conf['sectionA']['new_setting'] == 'valB'
1236
1237 caplog.clear()
1238
1239 # Assign new setting
1240 default_conf['sectionA']['new_setting'] = 'valA'
1241 # Delete deprecated setting
1242 del default_conf['sectionB']['deprecated_setting']
1243 process_deprecated_setting(default_conf,
1244 'sectionA', 'new_setting',
1245 'sectionB', 'deprecated_setting')
1246 assert not log_has_re('DEPRECATED', caplog)
1247 assert default_conf['sectionA']['new_setting'] == 'valA'
1248
1249
1250def test_process_removed_setting(mocker, default_conf, caplog):
1251 patched_configuration_load_config_file(mocker, default_conf)
1252
1253 # Create sections for new and deprecated settings
1254 # (they may not exist in the config)
1255 default_conf['sectionA'] = {}
1256 default_conf['sectionB'] = {}
1257 # Assign new setting
1258 default_conf['sectionB']['somesetting'] = 'valA'
1259
1260 # Only new setting exists (nothing should happen)
1261 process_removed_setting(default_conf,
1262 'sectionA', 'somesetting',
1263 'sectionB', 'somesetting')
1264 # Assign removed setting
1265 default_conf['sectionA']['somesetting'] = 'valB'
1266
1267 with pytest.raises(OperationalException,
1268 match=r"Setting .* has been moved"):
1269 process_removed_setting(default_conf,
1270 'sectionA', 'somesetting',
1271 'sectionB', 'somesetting')
1272
1273
1274def test_process_deprecated_ticker_interval(mocker, default_conf, caplog):
1275 message = "DEPRECATED: Please use 'timeframe' instead of 'ticker_interval."
1276 config = deepcopy(default_conf)
1277 process_temporary_deprecated_settings(config)
1278 assert not log_has(message, caplog)
1279
1280 del config['timeframe']
1281 config['ticker_interval'] = '15m'
1282 process_temporary_deprecated_settings(config)
1283 assert log_has(message, caplog)
1284 assert config['ticker_interval'] == '15m'
1285
1286 config = deepcopy(default_conf)
1287 # Have both timeframe and ticker interval in config
1288 # Can also happen when using ticker_interval in configuration, and --timeframe as cli argument
1289 config['timeframe'] = '5m'
1290 config['ticker_interval'] = '4h'
1291 with pytest.raises(OperationalException,
1292 match=r"Both 'timeframe' and 'ticker_interval' detected."):
1293 process_temporary_deprecated_settings(config)