Elffuss BraidHub

kikocis/freqtrade public

develop · 15.2 KiBRawPermalink
1# pragma pylint: disable=missing-docstring, protected-access, C0103
2import logging
3import warnings
4from base64 import urlsafe_b64encode
5from pathlib import Path
6
7import pytest
8from pandas import DataFrame
9
10from freqtrade.exceptions import OperationalException
11from freqtrade.resolvers import StrategyResolver
12from freqtrade.strategy.interface import IStrategy
13from tests.conftest import log_has, log_has_re
14
15
16def test_search_strategy():
17 default_location = Path(__file__).parent / 'strats'
18
19 s, _ = StrategyResolver._search_object(
20 directory=default_location,
21 object_name='DefaultStrategy',
22 add_source=True,
23 )
24 assert issubclass(s, IStrategy)
25
26 s, _ = StrategyResolver._search_object(
27 directory=default_location,
28 object_name='NotFoundStrategy',
29 add_source=True,
30 )
31 assert s is None
32
33
34def test_search_all_strategies_no_failed():
35 directory = Path(__file__).parent / "strats"
36 strategies = StrategyResolver.search_all_objects(directory, enum_failed=False)
37 assert isinstance(strategies, list)
38 assert len(strategies) == 3
39 assert isinstance(strategies[0], dict)
40
41
42def test_search_all_strategies_with_failed():
43 directory = Path(__file__).parent / "strats"
44 strategies = StrategyResolver.search_all_objects(directory, enum_failed=True)
45 assert isinstance(strategies, list)
46 assert len(strategies) == 4
47 # with enum_failed=True search_all_objects() shall find 2 good strategies
48 # and 1 which fails to load
49 assert len([x for x in strategies if x['class'] is not None]) == 3
50 assert len([x for x in strategies if x['class'] is None]) == 1
51
52
53def test_load_strategy(default_conf, result):
54 default_conf.update({'strategy': 'SampleStrategy',
55 'strategy_path': str(Path(__file__).parents[2] / 'freqtrade/templates')
56 })
57 strategy = StrategyResolver.load_strategy(default_conf)
58 assert isinstance(strategy.__source__, str)
59 assert 'class SampleStrategy' in strategy.__source__
60 assert isinstance(strategy.__file__, str)
61 assert 'rsi' in strategy.advise_indicators(result, {'pair': 'ETH/BTC'})
62
63
64def test_load_strategy_base64(result, caplog, default_conf):
65 with (Path(__file__).parents[2] / 'freqtrade/templates/sample_strategy.py').open("rb") as file:
66 encoded_string = urlsafe_b64encode(file.read()).decode("utf-8")
67 default_conf.update({'strategy': 'SampleStrategy:{}'.format(encoded_string)})
68
69 strategy = StrategyResolver.load_strategy(default_conf)
70 assert 'rsi' in strategy.advise_indicators(result, {'pair': 'ETH/BTC'})
71 # Make sure strategy was loaded from base64 (using temp directory)!!
72 assert log_has_re(r"Using resolved strategy SampleStrategy from '"
73 r".*(/|\\).*(/|\\)SampleStrategy\.py'\.\.\.", caplog)
74
75
76def test_load_strategy_invalid_directory(result, caplog, default_conf):
77 default_conf['strategy'] = 'DefaultStrategy'
78 extra_dir = Path.cwd() / 'some/path'
79 with pytest.raises(OperationalException):
80 StrategyResolver._load_strategy('DefaultStrategy', config=default_conf,
81 extra_dir=extra_dir)
82
83 assert log_has_re(r'Path .*' + r'some.*path.*' + r'.* does not exist', caplog)
84
85
86def test_load_not_found_strategy(default_conf):
87 default_conf['strategy'] = 'NotFoundStrategy'
88 with pytest.raises(OperationalException,
89 match=r"Impossible to load Strategy 'NotFoundStrategy'. "
90 r"This class does not exist or contains Python code errors."):
91 StrategyResolver.load_strategy(default_conf)
92
93
94def test_load_strategy_noname(default_conf):
95 default_conf['strategy'] = ''
96 with pytest.raises(OperationalException,
97 match="No strategy set. Please use `--strategy` to specify "
98 "the strategy class to use."):
99 StrategyResolver.load_strategy(default_conf)
100
101
102def test_strategy(result, default_conf):
103 default_conf.update({'strategy': 'DefaultStrategy'})
104
105 strategy = StrategyResolver.load_strategy(default_conf)
106 metadata = {'pair': 'ETH/BTC'}
107 assert strategy.minimal_roi[0] == 0.04
108 assert default_conf["minimal_roi"]['0'] == 0.04
109
110 assert strategy.stoploss == -0.10
111 assert default_conf['stoploss'] == -0.10
112
113 assert strategy.timeframe == '5m'
114 assert strategy.ticker_interval == '5m'
115 assert default_conf['timeframe'] == '5m'
116
117 df_indicators = strategy.advise_indicators(result, metadata=metadata)
118 assert 'adx' in df_indicators
119
120 dataframe = strategy.advise_buy(df_indicators, metadata=metadata)
121 assert 'buy' in dataframe.columns
122
123 dataframe = strategy.advise_sell(df_indicators, metadata=metadata)
124 assert 'sell' in dataframe.columns
125
126
127def test_strategy_override_minimal_roi(caplog, default_conf):
128 caplog.set_level(logging.INFO)
129 default_conf.update({
130 'strategy': 'DefaultStrategy',
131 'minimal_roi': {
132 "0": 0.5
133 }
134 })
135 strategy = StrategyResolver.load_strategy(default_conf)
136
137 assert strategy.minimal_roi[0] == 0.5
138 assert log_has("Override strategy 'minimal_roi' with value in config file: {'0': 0.5}.", caplog)
139
140
141def test_strategy_override_stoploss(caplog, default_conf):
142 caplog.set_level(logging.INFO)
143 default_conf.update({
144 'strategy': 'DefaultStrategy',
145 'stoploss': -0.5
146 })
147 strategy = StrategyResolver.load_strategy(default_conf)
148
149 assert strategy.stoploss == -0.5
150 assert log_has("Override strategy 'stoploss' with value in config file: -0.5.", caplog)
151
152
153def test_strategy_override_trailing_stop(caplog, default_conf):
154 caplog.set_level(logging.INFO)
155 default_conf.update({
156 'strategy': 'DefaultStrategy',
157 'trailing_stop': True
158 })
159 strategy = StrategyResolver.load_strategy(default_conf)
160
161 assert strategy.trailing_stop
162 assert isinstance(strategy.trailing_stop, bool)
163 assert log_has("Override strategy 'trailing_stop' with value in config file: True.", caplog)
164
165
166def test_strategy_override_trailing_stop_positive(caplog, default_conf):
167 caplog.set_level(logging.INFO)
168 default_conf.update({
169 'strategy': 'DefaultStrategy',
170 'trailing_stop_positive': -0.1,
171 'trailing_stop_positive_offset': -0.2
172
173 })
174 strategy = StrategyResolver.load_strategy(default_conf)
175
176 assert strategy.trailing_stop_positive == -0.1
177 assert log_has("Override strategy 'trailing_stop_positive' with value in config file: -0.1.",
178 caplog)
179
180 assert strategy.trailing_stop_positive_offset == -0.2
181 assert log_has("Override strategy 'trailing_stop_positive' with value in config file: -0.1.",
182 caplog)
183
184
185def test_strategy_override_timeframe(caplog, default_conf):
186 caplog.set_level(logging.INFO)
187
188 default_conf.update({
189 'strategy': 'DefaultStrategy',
190 'timeframe': 60,
191 'stake_currency': 'ETH'
192 })
193 strategy = StrategyResolver.load_strategy(default_conf)
194
195 assert strategy.timeframe == 60
196 assert strategy.stake_currency == 'ETH'
197 assert log_has("Override strategy 'timeframe' with value in config file: 60.",
198 caplog)
199
200
201def test_strategy_override_process_only_new_candles(caplog, default_conf):
202 caplog.set_level(logging.INFO)
203
204 default_conf.update({
205 'strategy': 'DefaultStrategy',
206 'process_only_new_candles': True
207 })
208 strategy = StrategyResolver.load_strategy(default_conf)
209
210 assert strategy.process_only_new_candles
211 assert log_has("Override strategy 'process_only_new_candles' with value in config file: True.",
212 caplog)
213
214
215def test_strategy_override_order_types(caplog, default_conf):
216 caplog.set_level(logging.INFO)
217
218 order_types = {
219 'buy': 'market',
220 'sell': 'limit',
221 'stoploss': 'limit',
222 'stoploss_on_exchange': True,
223 }
224 default_conf.update({
225 'strategy': 'DefaultStrategy',
226 'order_types': order_types
227 })
228 strategy = StrategyResolver.load_strategy(default_conf)
229
230 assert strategy.order_types
231 for method in ['buy', 'sell', 'stoploss', 'stoploss_on_exchange']:
232 assert strategy.order_types[method] == order_types[method]
233
234 assert log_has("Override strategy 'order_types' with value in config file:"
235 " {'buy': 'market', 'sell': 'limit', 'stoploss': 'limit',"
236 " 'stoploss_on_exchange': True}.", caplog)
237
238 default_conf.update({
239 'strategy': 'DefaultStrategy',
240 'order_types': {'buy': 'market'}
241 })
242 # Raise error for invalid configuration
243 with pytest.raises(ImportError,
244 match=r"Impossible to load Strategy 'DefaultStrategy'. "
245 r"Order-types mapping is incomplete."):
246 StrategyResolver.load_strategy(default_conf)
247
248
249def test_strategy_override_order_tif(caplog, default_conf):
250 caplog.set_level(logging.INFO)
251
252 order_time_in_force = {
253 'buy': 'fok',
254 'sell': 'gtc',
255 }
256
257 default_conf.update({
258 'strategy': 'DefaultStrategy',
259 'order_time_in_force': order_time_in_force
260 })
261 strategy = StrategyResolver.load_strategy(default_conf)
262
263 assert strategy.order_time_in_force
264 for method in ['buy', 'sell']:
265 assert strategy.order_time_in_force[method] == order_time_in_force[method]
266
267 assert log_has("Override strategy 'order_time_in_force' with value in config file:"
268 " {'buy': 'fok', 'sell': 'gtc'}.", caplog)
269
270 default_conf.update({
271 'strategy': 'DefaultStrategy',
272 'order_time_in_force': {'buy': 'fok'}
273 })
274 # Raise error for invalid configuration
275 with pytest.raises(ImportError,
276 match=r"Impossible to load Strategy 'DefaultStrategy'. "
277 r"Order-time-in-force mapping is incomplete."):
278 StrategyResolver.load_strategy(default_conf)
279
280
281def test_strategy_override_use_sell_signal(caplog, default_conf):
282 caplog.set_level(logging.INFO)
283 default_conf.update({
284 'strategy': 'DefaultStrategy',
285 })
286 strategy = StrategyResolver.load_strategy(default_conf)
287 assert strategy.use_sell_signal
288 assert isinstance(strategy.use_sell_signal, bool)
289 # must be inserted to configuration
290 assert 'use_sell_signal' in default_conf['ask_strategy']
291 assert default_conf['ask_strategy']['use_sell_signal']
292
293 default_conf.update({
294 'strategy': 'DefaultStrategy',
295 'ask_strategy': {
296 'use_sell_signal': False,
297 },
298 })
299 strategy = StrategyResolver.load_strategy(default_conf)
300
301 assert not strategy.use_sell_signal
302 assert isinstance(strategy.use_sell_signal, bool)
303 assert log_has("Override strategy 'use_sell_signal' with value in config file: False.", caplog)
304
305
306def test_strategy_override_use_sell_profit_only(caplog, default_conf):
307 caplog.set_level(logging.INFO)
308 default_conf.update({
309 'strategy': 'DefaultStrategy',
310 })
311 strategy = StrategyResolver.load_strategy(default_conf)
312 assert not strategy.sell_profit_only
313 assert isinstance(strategy.sell_profit_only, bool)
314 # must be inserted to configuration
315 assert 'sell_profit_only' in default_conf['ask_strategy']
316 assert not default_conf['ask_strategy']['sell_profit_only']
317
318 default_conf.update({
319 'strategy': 'DefaultStrategy',
320 'ask_strategy': {
321 'sell_profit_only': True,
322 },
323 })
324 strategy = StrategyResolver.load_strategy(default_conf)
325
326 assert strategy.sell_profit_only
327 assert isinstance(strategy.sell_profit_only, bool)
328 assert log_has("Override strategy 'sell_profit_only' with value in config file: True.", caplog)
329
330
331@pytest.mark.filterwarnings("ignore:deprecated")
332def test_deprecate_populate_indicators(result, default_conf):
333 default_location = Path(__file__).parent / "strats"
334 default_conf.update({'strategy': 'TestStrategyLegacy',
335 'strategy_path': default_location})
336 strategy = StrategyResolver.load_strategy(default_conf)
337 with warnings.catch_warnings(record=True) as w:
338 # Cause all warnings to always be triggered.
339 warnings.simplefilter("always")
340 indicators = strategy.advise_indicators(result, {'pair': 'ETH/BTC'})
341 assert len(w) == 1
342 assert issubclass(w[-1].category, DeprecationWarning)
343 assert "deprecated - check out the Sample strategy to see the current function headers!" \
344 in str(w[-1].message)
345
346 with warnings.catch_warnings(record=True) as w:
347 # Cause all warnings to always be triggered.
348 warnings.simplefilter("always")
349 strategy.advise_buy(indicators, {'pair': 'ETH/BTC'})
350 assert len(w) == 1
351 assert issubclass(w[-1].category, DeprecationWarning)
352 assert "deprecated - check out the Sample strategy to see the current function headers!" \
353 in str(w[-1].message)
354
355 with warnings.catch_warnings(record=True) as w:
356 # Cause all warnings to always be triggered.
357 warnings.simplefilter("always")
358 strategy.advise_sell(indicators, {'pair': 'ETH_BTC'})
359 assert len(w) == 1
360 assert issubclass(w[-1].category, DeprecationWarning)
361 assert "deprecated - check out the Sample strategy to see the current function headers!" \
362 in str(w[-1].message)
363
364
365@pytest.mark.filterwarnings("ignore:deprecated")
366def test_call_deprecated_function(result, monkeypatch, default_conf, caplog):
367 default_location = Path(__file__).parent / "strats"
368 del default_conf['timeframe']
369 default_conf.update({'strategy': 'TestStrategyLegacy',
370 'strategy_path': default_location})
371 strategy = StrategyResolver.load_strategy(default_conf)
372 metadata = {'pair': 'ETH/BTC'}
373
374 # Make sure we are using a legacy function
375 assert strategy._populate_fun_len == 2
376 assert strategy._buy_fun_len == 2
377 assert strategy._sell_fun_len == 2
378 assert strategy.INTERFACE_VERSION == 1
379 assert strategy.timeframe == '5m'
380 assert strategy.ticker_interval == '5m'
381
382 indicator_df = strategy.advise_indicators(result, metadata=metadata)
383 assert isinstance(indicator_df, DataFrame)
384 assert 'adx' in indicator_df.columns
385
386 buydf = strategy.advise_buy(result, metadata=metadata)
387 assert isinstance(buydf, DataFrame)
388 assert 'buy' in buydf.columns
389
390 selldf = strategy.advise_sell(result, metadata=metadata)
391 assert isinstance(selldf, DataFrame)
392 assert 'sell' in selldf
393
394 assert log_has("DEPRECATED: Please migrate to using 'timeframe' instead of 'ticker_interval'.",
395 caplog)
396
397
398def test_strategy_interface_versioning(result, monkeypatch, default_conf):
399 default_conf.update({'strategy': 'DefaultStrategy'})
400 strategy = StrategyResolver.load_strategy(default_conf)
401 metadata = {'pair': 'ETH/BTC'}
402
403 # Make sure we are using a legacy function
404 assert strategy._populate_fun_len == 3
405 assert strategy._buy_fun_len == 3
406 assert strategy._sell_fun_len == 3
407 assert strategy.INTERFACE_VERSION == 2
408
409 indicator_df = strategy.advise_indicators(result, metadata=metadata)
410 assert isinstance(indicator_df, DataFrame)
411 assert 'adx' in indicator_df.columns
412
413 buydf = strategy.advise_buy(result, metadata=metadata)
414 assert isinstance(buydf, DataFrame)
415 assert 'buy' in buydf.columns
416
417 selldf = strategy.advise_sell(result, metadata=metadata)
418 assert isinstance(selldf, DataFrame)
419 assert 'sell' in selldf