| 1 | # pragma pylint: disable=missing-docstring, C0103 |
| 2 | import logging |
| 3 | from datetime import datetime, timedelta, timezone |
| 4 | from unittest.mock import MagicMock |
| 5 | |
| 6 | import arrow |
| 7 | import pytest |
| 8 | from pandas import DataFrame |
| 9 | |
| 10 | from freqtrade.configuration import TimeRange |
| 11 | from freqtrade.data.dataprovider import DataProvider |
| 12 | from freqtrade.data.history import load_data |
| 13 | from freqtrade.exceptions import OperationalException, StrategyError |
| 14 | from freqtrade.persistence import PairLocks, Trade |
| 15 | from freqtrade.resolvers import StrategyResolver |
| 16 | from freqtrade.strategy.hyper import (BaseParameter, CategoricalParameter, DecimalParameter, |
| 17 | IntParameter, RealParameter) |
| 18 | from freqtrade.strategy.interface import SellCheckTuple, SellType |
| 19 | from freqtrade.strategy.strategy_wrapper import strategy_safe_wrapper |
| 20 | from tests.conftest import log_has, log_has_re |
| 21 | |
| 22 | from .strats.default_strategy import DefaultStrategy |
| 23 | |
| 24 | |
| 25 | # Avoid to reinit the same object again and again |
| 26 | _STRATEGY = DefaultStrategy(config={}) |
| 27 | _STRATEGY.dp = DataProvider({}, None, None) |
| 28 | |
| 29 | |
| 30 | def test_returns_latest_signal(mocker, default_conf, ohlcv_history): |
| 31 | ohlcv_history.loc[1, 'date'] = arrow.utcnow() |
| 32 | # Take a copy to correctly modify the call |
| 33 | mocked_history = ohlcv_history.copy() |
| 34 | mocked_history['sell'] = 0 |
| 35 | mocked_history['buy'] = 0 |
| 36 | mocked_history.loc[1, 'sell'] = 1 |
| 37 | |
| 38 | assert _STRATEGY.get_signal('ETH/BTC', '5m', mocked_history) == (False, True) |
| 39 | mocked_history.loc[1, 'sell'] = 0 |
| 40 | mocked_history.loc[1, 'buy'] = 1 |
| 41 | |
| 42 | assert _STRATEGY.get_signal('ETH/BTC', '5m', mocked_history) == (True, False) |
| 43 | mocked_history.loc[1, 'sell'] = 0 |
| 44 | mocked_history.loc[1, 'buy'] = 0 |
| 45 | |
| 46 | assert _STRATEGY.get_signal('ETH/BTC', '5m', mocked_history) == (False, False) |
| 47 | |
| 48 | |
| 49 | def test_analyze_pair_empty(default_conf, mocker, caplog, ohlcv_history): |
| 50 | mocker.patch.object(_STRATEGY.dp, 'ohlcv', return_value=ohlcv_history) |
| 51 | mocker.patch.object( |
| 52 | _STRATEGY, '_analyze_ticker_internal', |
| 53 | return_value=DataFrame([]) |
| 54 | ) |
| 55 | mocker.patch.object(_STRATEGY, 'assert_df') |
| 56 | |
| 57 | _STRATEGY.analyze_pair('ETH/BTC') |
| 58 | |
| 59 | assert log_has('Empty dataframe for pair ETH/BTC', caplog) |
| 60 | |
| 61 | |
| 62 | def test_get_signal_empty(default_conf, mocker, caplog): |
| 63 | assert (False, False) == _STRATEGY.get_signal('foo', default_conf['timeframe'], DataFrame()) |
| 64 | assert log_has('Empty candle (OHLCV) data for pair foo', caplog) |
| 65 | caplog.clear() |
| 66 | |
| 67 | assert (False, False) == _STRATEGY.get_signal('bar', default_conf['timeframe'], None) |
| 68 | assert log_has('Empty candle (OHLCV) data for pair bar', caplog) |
| 69 | caplog.clear() |
| 70 | |
| 71 | assert (False, False) == _STRATEGY.get_signal('baz', default_conf['timeframe'], DataFrame([])) |
| 72 | assert log_has('Empty candle (OHLCV) data for pair baz', caplog) |
| 73 | |
| 74 | |
| 75 | def test_get_signal_exception_valueerror(default_conf, mocker, caplog, ohlcv_history): |
| 76 | caplog.set_level(logging.INFO) |
| 77 | mocker.patch.object(_STRATEGY.dp, 'ohlcv', return_value=ohlcv_history) |
| 78 | mocker.patch.object( |
| 79 | _STRATEGY, '_analyze_ticker_internal', |
| 80 | side_effect=ValueError('xyz') |
| 81 | ) |
| 82 | _STRATEGY.analyze_pair('foo') |
| 83 | assert log_has_re(r'Strategy caused the following exception: xyz.*', caplog) |
| 84 | caplog.clear() |
| 85 | |
| 86 | mocker.patch.object( |
| 87 | _STRATEGY, 'analyze_ticker', |
| 88 | side_effect=Exception('invalid ticker history ') |
| 89 | ) |
| 90 | _STRATEGY.analyze_pair('foo') |
| 91 | assert log_has_re(r'Strategy caused the following exception: xyz.*', caplog) |
| 92 | |
| 93 | |
| 94 | def test_get_signal_old_dataframe(default_conf, mocker, caplog, ohlcv_history): |
| 95 | # default_conf defines a 5m interval. we check interval * 2 + 5m |
| 96 | # this is necessary as the last candle is removed (partial candles) by default |
| 97 | ohlcv_history.loc[1, 'date'] = arrow.utcnow().shift(minutes=-16) |
| 98 | # Take a copy to correctly modify the call |
| 99 | mocked_history = ohlcv_history.copy() |
| 100 | mocked_history['sell'] = 0 |
| 101 | mocked_history['buy'] = 0 |
| 102 | mocked_history.loc[1, 'buy'] = 1 |
| 103 | |
| 104 | caplog.set_level(logging.INFO) |
| 105 | mocker.patch.object(_STRATEGY, 'assert_df') |
| 106 | |
| 107 | assert (False, False) == _STRATEGY.get_signal('xyz', default_conf['timeframe'], mocked_history) |
| 108 | assert log_has('Outdated history for pair xyz. Last tick is 16 minutes old', caplog) |
| 109 | |
| 110 | |
| 111 | def test_ignore_expired_candle(default_conf): |
| 112 | default_conf.update({'strategy': 'DefaultStrategy'}) |
| 113 | strategy = StrategyResolver.load_strategy(default_conf) |
| 114 | strategy.ignore_buying_expired_candle_after = 60 |
| 115 | |
| 116 | latest_date = datetime(2020, 12, 30, 7, 0, 0, tzinfo=timezone.utc) |
| 117 | # Add 1 candle length as the "latest date" defines candle open. |
| 118 | current_time = latest_date + timedelta(seconds=80 + 300) |
| 119 | |
| 120 | assert strategy.ignore_expired_candle(latest_date=latest_date, |
| 121 | current_time=current_time, |
| 122 | timeframe_seconds=300, |
| 123 | buy=True) is True |
| 124 | |
| 125 | current_time = latest_date + timedelta(seconds=30 + 300) |
| 126 | |
| 127 | assert not strategy.ignore_expired_candle(latest_date=latest_date, |
| 128 | current_time=current_time, |
| 129 | timeframe_seconds=300, |
| 130 | buy=True) is True |
| 131 | |
| 132 | |
| 133 | def test_assert_df_raise(mocker, caplog, ohlcv_history): |
| 134 | ohlcv_history.loc[1, 'date'] = arrow.utcnow().shift(minutes=-16) |
| 135 | # Take a copy to correctly modify the call |
| 136 | mocked_history = ohlcv_history.copy() |
| 137 | mocked_history['sell'] = 0 |
| 138 | mocked_history['buy'] = 0 |
| 139 | mocked_history.loc[1, 'buy'] = 1 |
| 140 | |
| 141 | caplog.set_level(logging.INFO) |
| 142 | mocker.patch.object(_STRATEGY.dp, 'ohlcv', return_value=ohlcv_history) |
| 143 | mocker.patch.object(_STRATEGY.dp, 'get_analyzed_dataframe', return_value=(mocked_history, 0)) |
| 144 | mocker.patch.object( |
| 145 | _STRATEGY, 'assert_df', |
| 146 | side_effect=StrategyError('Dataframe returned...') |
| 147 | ) |
| 148 | _STRATEGY.analyze_pair('xyz') |
| 149 | assert log_has('Unable to analyze candle (OHLCV) data for pair xyz: Dataframe returned...', |
| 150 | caplog) |
| 151 | |
| 152 | |
| 153 | def test_assert_df(ohlcv_history, caplog): |
| 154 | df_len = len(ohlcv_history) - 1 |
| 155 | # Ensure it's running when passed correctly |
| 156 | _STRATEGY.assert_df(ohlcv_history, len(ohlcv_history), |
| 157 | ohlcv_history.loc[df_len, 'close'], ohlcv_history.loc[df_len, 'date']) |
| 158 | |
| 159 | with pytest.raises(StrategyError, match=r"Dataframe returned from strategy.*length\."): |
| 160 | _STRATEGY.assert_df(ohlcv_history, len(ohlcv_history) + 1, |
| 161 | ohlcv_history.loc[df_len, 'close'], ohlcv_history.loc[df_len, 'date']) |
| 162 | |
| 163 | with pytest.raises(StrategyError, |
| 164 | match=r"Dataframe returned from strategy.*last close price\."): |
| 165 | _STRATEGY.assert_df(ohlcv_history, len(ohlcv_history), |
| 166 | ohlcv_history.loc[df_len, 'close'] + 0.01, |
| 167 | ohlcv_history.loc[df_len, 'date']) |
| 168 | with pytest.raises(StrategyError, |
| 169 | match=r"Dataframe returned from strategy.*last date\."): |
| 170 | _STRATEGY.assert_df(ohlcv_history, len(ohlcv_history), |
| 171 | ohlcv_history.loc[df_len, 'close'], ohlcv_history.loc[0, 'date']) |
| 172 | |
| 173 | _STRATEGY.disable_dataframe_checks = True |
| 174 | caplog.clear() |
| 175 | _STRATEGY.assert_df(ohlcv_history, len(ohlcv_history), |
| 176 | ohlcv_history.loc[2, 'close'], ohlcv_history.loc[0, 'date']) |
| 177 | assert log_has_re(r"Dataframe returned from strategy.*last date\.", caplog) |
| 178 | # reset to avoid problems in other tests due to test leakage |
| 179 | _STRATEGY.disable_dataframe_checks = False |
| 180 | |
| 181 | |
| 182 | def test_ohlcvdata_to_dataframe(default_conf, testdatadir) -> None: |
| 183 | default_conf.update({'strategy': 'DefaultStrategy'}) |
| 184 | strategy = StrategyResolver.load_strategy(default_conf) |
| 185 | |
| 186 | timerange = TimeRange.parse_timerange('1510694220-1510700340') |
| 187 | data = load_data(testdatadir, '1m', ['UNITTEST/BTC'], timerange=timerange, |
| 188 | fill_up_missing=True) |
| 189 | processed = strategy.ohlcvdata_to_dataframe(data) |
| 190 | assert len(processed['UNITTEST/BTC']) == 102 # partial candle was removed |
| 191 | |
| 192 | |
| 193 | def test_ohlcvdata_to_dataframe_copy(mocker, default_conf, testdatadir) -> None: |
| 194 | default_conf.update({'strategy': 'DefaultStrategy'}) |
| 195 | strategy = StrategyResolver.load_strategy(default_conf) |
| 196 | aimock = mocker.patch('freqtrade.strategy.interface.IStrategy.advise_indicators') |
| 197 | timerange = TimeRange.parse_timerange('1510694220-1510700340') |
| 198 | data = load_data(testdatadir, '1m', ['UNITTEST/BTC'], timerange=timerange, |
| 199 | fill_up_missing=True) |
| 200 | strategy.ohlcvdata_to_dataframe(data) |
| 201 | assert aimock.call_count == 1 |
| 202 | # Ensure that a copy of the dataframe is passed to advice_indicators |
| 203 | assert aimock.call_args_list[0][0][0] is not data |
| 204 | |
| 205 | |
| 206 | def test_min_roi_reached(default_conf, fee) -> None: |
| 207 | |
| 208 | # Use list to confirm sequence does not matter |
| 209 | min_roi_list = [{20: 0.05, 55: 0.01, 0: 0.1}, |
| 210 | {0: 0.1, 20: 0.05, 55: 0.01}] |
| 211 | for roi in min_roi_list: |
| 212 | default_conf.update({'strategy': 'DefaultStrategy'}) |
| 213 | strategy = StrategyResolver.load_strategy(default_conf) |
| 214 | strategy.minimal_roi = roi |
| 215 | trade = Trade( |
| 216 | pair='ETH/BTC', |
| 217 | stake_amount=0.001, |
| 218 | amount=5, |
| 219 | open_date=arrow.utcnow().shift(hours=-1).datetime, |
| 220 | fee_open=fee.return_value, |
| 221 | fee_close=fee.return_value, |
| 222 | exchange='binance', |
| 223 | open_rate=1, |
| 224 | ) |
| 225 | |
| 226 | assert not strategy.min_roi_reached(trade, 0.02, arrow.utcnow().shift(minutes=-56).datetime) |
| 227 | assert strategy.min_roi_reached(trade, 0.12, arrow.utcnow().shift(minutes=-56).datetime) |
| 228 | |
| 229 | assert not strategy.min_roi_reached(trade, 0.04, arrow.utcnow().shift(minutes=-39).datetime) |
| 230 | assert strategy.min_roi_reached(trade, 0.06, arrow.utcnow().shift(minutes=-39).datetime) |
| 231 | |
| 232 | assert not strategy.min_roi_reached(trade, -0.01, arrow.utcnow().shift(minutes=-1).datetime) |
| 233 | assert strategy.min_roi_reached(trade, 0.02, arrow.utcnow().shift(minutes=-1).datetime) |
| 234 | |
| 235 | |
| 236 | def test_min_roi_reached2(default_conf, fee) -> None: |
| 237 | |
| 238 | # test with ROI raising after last interval |
| 239 | min_roi_list = [{20: 0.07, |
| 240 | 30: 0.05, |
| 241 | 55: 0.30, |
| 242 | 0: 0.1 |
| 243 | }, |
| 244 | {0: 0.1, |
| 245 | 20: 0.07, |
| 246 | 30: 0.05, |
| 247 | 55: 0.30 |
| 248 | }, |
| 249 | ] |
| 250 | for roi in min_roi_list: |
| 251 | default_conf.update({'strategy': 'DefaultStrategy'}) |
| 252 | strategy = StrategyResolver.load_strategy(default_conf) |
| 253 | strategy.minimal_roi = roi |
| 254 | trade = Trade( |
| 255 | pair='ETH/BTC', |
| 256 | stake_amount=0.001, |
| 257 | amount=5, |
| 258 | open_date=arrow.utcnow().shift(hours=-1).datetime, |
| 259 | fee_open=fee.return_value, |
| 260 | fee_close=fee.return_value, |
| 261 | exchange='binance', |
| 262 | open_rate=1, |
| 263 | ) |
| 264 | |
| 265 | assert not strategy.min_roi_reached(trade, 0.02, arrow.utcnow().shift(minutes=-56).datetime) |
| 266 | assert strategy.min_roi_reached(trade, 0.12, arrow.utcnow().shift(minutes=-56).datetime) |
| 267 | |
| 268 | assert not strategy.min_roi_reached(trade, 0.04, arrow.utcnow().shift(minutes=-39).datetime) |
| 269 | assert strategy.min_roi_reached(trade, 0.071, arrow.utcnow().shift(minutes=-39).datetime) |
| 270 | |
| 271 | assert not strategy.min_roi_reached(trade, 0.04, arrow.utcnow().shift(minutes=-26).datetime) |
| 272 | assert strategy.min_roi_reached(trade, 0.06, arrow.utcnow().shift(minutes=-26).datetime) |
| 273 | |
| 274 | # Should not trigger with 20% profit since after 55 minutes only 30% is active. |
| 275 | assert not strategy.min_roi_reached(trade, 0.20, arrow.utcnow().shift(minutes=-2).datetime) |
| 276 | assert strategy.min_roi_reached(trade, 0.31, arrow.utcnow().shift(minutes=-2).datetime) |
| 277 | |
| 278 | |
| 279 | def test_min_roi_reached3(default_conf, fee) -> None: |
| 280 | |
| 281 | # test for issue #1948 |
| 282 | min_roi = {20: 0.07, |
| 283 | 30: 0.05, |
| 284 | 55: 0.30, |
| 285 | } |
| 286 | default_conf.update({'strategy': 'DefaultStrategy'}) |
| 287 | strategy = StrategyResolver.load_strategy(default_conf) |
| 288 | strategy.minimal_roi = min_roi |
| 289 | trade = Trade( |
| 290 | pair='ETH/BTC', |
| 291 | stake_amount=0.001, |
| 292 | amount=5, |
| 293 | open_date=arrow.utcnow().shift(hours=-1).datetime, |
| 294 | fee_open=fee.return_value, |
| 295 | fee_close=fee.return_value, |
| 296 | exchange='binance', |
| 297 | open_rate=1, |
| 298 | ) |
| 299 | |
| 300 | assert not strategy.min_roi_reached(trade, 0.02, arrow.utcnow().shift(minutes=-56).datetime) |
| 301 | assert not strategy.min_roi_reached(trade, 0.12, arrow.utcnow().shift(minutes=-56).datetime) |
| 302 | |
| 303 | assert not strategy.min_roi_reached(trade, 0.04, arrow.utcnow().shift(minutes=-39).datetime) |
| 304 | assert strategy.min_roi_reached(trade, 0.071, arrow.utcnow().shift(minutes=-39).datetime) |
| 305 | |
| 306 | assert not strategy.min_roi_reached(trade, 0.04, arrow.utcnow().shift(minutes=-26).datetime) |
| 307 | assert strategy.min_roi_reached(trade, 0.06, arrow.utcnow().shift(minutes=-26).datetime) |
| 308 | |
| 309 | # Should not trigger with 20% profit since after 55 minutes only 30% is active. |
| 310 | assert not strategy.min_roi_reached(trade, 0.20, arrow.utcnow().shift(minutes=-2).datetime) |
| 311 | assert strategy.min_roi_reached(trade, 0.31, arrow.utcnow().shift(minutes=-2).datetime) |
| 312 | |
| 313 | |
| 314 | @pytest.mark.parametrize( |
| 315 | 'profit,adjusted,expected,trailing,custom,profit2,adjusted2,expected2,custom_stop', [ |
| 316 | # Profit, adjusted stoploss(absolute), profit for 2nd call, enable trailing, |
| 317 | # enable custom stoploss, expected after 1st call, expected after 2nd call |
| 318 | (0.2, 0.9, SellType.NONE, False, False, 0.3, 0.9, SellType.NONE, None), |
| 319 | (0.2, 0.9, SellType.NONE, False, False, -0.2, 0.9, SellType.STOP_LOSS, None), |
| 320 | (0.2, 1.14, SellType.NONE, True, False, 0.05, 1.14, SellType.TRAILING_STOP_LOSS, None), |
| 321 | (0.01, 0.96, SellType.NONE, True, False, 0.05, 1, SellType.NONE, None), |
| 322 | (0.05, 1, SellType.NONE, True, False, -0.01, 1, SellType.TRAILING_STOP_LOSS, None), |
| 323 | # Default custom case - trails with 10% |
| 324 | (0.05, 0.95, SellType.NONE, False, True, -0.02, 0.95, SellType.NONE, None), |
| 325 | (0.05, 0.95, SellType.NONE, False, True, -0.06, 0.95, SellType.TRAILING_STOP_LOSS, None), |
| 326 | (0.05, 1, SellType.NONE, False, True, -0.06, 1, SellType.TRAILING_STOP_LOSS, |
| 327 | lambda **kwargs: -0.05), |
| 328 | (0.05, 1, SellType.NONE, False, True, 0.09, 1.04, SellType.NONE, |
| 329 | lambda **kwargs: -0.05), |
| 330 | (0.05, 0.95, SellType.NONE, False, True, 0.09, 0.98, SellType.NONE, |
| 331 | lambda current_profit, **kwargs: -0.1 if current_profit < 0.6 else -(current_profit * 2)), |
| 332 | # Error case - static stoploss in place |
| 333 | (0.05, 0.9, SellType.NONE, False, True, 0.09, 0.9, SellType.NONE, |
| 334 | lambda **kwargs: None), |
| 335 | ]) |
| 336 | def test_stop_loss_reached(default_conf, fee, profit, adjusted, expected, trailing, custom, |
| 337 | profit2, adjusted2, expected2, custom_stop) -> None: |
| 338 | |
| 339 | default_conf.update({'strategy': 'DefaultStrategy'}) |
| 340 | |
| 341 | strategy = StrategyResolver.load_strategy(default_conf) |
| 342 | trade = Trade( |
| 343 | pair='ETH/BTC', |
| 344 | stake_amount=0.01, |
| 345 | amount=1, |
| 346 | open_date=arrow.utcnow().shift(hours=-1).datetime, |
| 347 | fee_open=fee.return_value, |
| 348 | fee_close=fee.return_value, |
| 349 | exchange='binance', |
| 350 | open_rate=1, |
| 351 | ) |
| 352 | trade.adjust_min_max_rates(trade.open_rate) |
| 353 | strategy.trailing_stop = trailing |
| 354 | strategy.trailing_stop_positive = -0.05 |
| 355 | strategy.use_custom_stoploss = custom |
| 356 | original_stopvalue = strategy.custom_stoploss |
| 357 | if custom_stop: |
| 358 | strategy.custom_stoploss = custom_stop |
| 359 | |
| 360 | now = arrow.utcnow().datetime |
| 361 | sl_flag = strategy.stop_loss_reached(current_rate=trade.open_rate * (1 + profit), trade=trade, |
| 362 | current_time=now, current_profit=profit, |
| 363 | force_stoploss=0, high=None) |
| 364 | assert isinstance(sl_flag, SellCheckTuple) |
| 365 | assert sl_flag.sell_type == expected |
| 366 | if expected == SellType.NONE: |
| 367 | assert sl_flag.sell_flag is False |
| 368 | else: |
| 369 | assert sl_flag.sell_flag is True |
| 370 | assert round(trade.stop_loss, 2) == adjusted |
| 371 | |
| 372 | sl_flag = strategy.stop_loss_reached(current_rate=trade.open_rate * (1 + profit2), trade=trade, |
| 373 | current_time=now, current_profit=profit2, |
| 374 | force_stoploss=0, high=None) |
| 375 | assert sl_flag.sell_type == expected2 |
| 376 | if expected2 == SellType.NONE: |
| 377 | assert sl_flag.sell_flag is False |
| 378 | else: |
| 379 | assert sl_flag.sell_flag is True |
| 380 | assert round(trade.stop_loss, 2) == adjusted2 |
| 381 | |
| 382 | strategy.custom_stoploss = original_stopvalue |
| 383 | |
| 384 | |
| 385 | def test_analyze_ticker_default(ohlcv_history, mocker, caplog) -> None: |
| 386 | caplog.set_level(logging.DEBUG) |
| 387 | ind_mock = MagicMock(side_effect=lambda x, meta: x) |
| 388 | buy_mock = MagicMock(side_effect=lambda x, meta: x) |
| 389 | sell_mock = MagicMock(side_effect=lambda x, meta: x) |
| 390 | mocker.patch.multiple( |
| 391 | 'freqtrade.strategy.interface.IStrategy', |
| 392 | advise_indicators=ind_mock, |
| 393 | advise_buy=buy_mock, |
| 394 | advise_sell=sell_mock, |
| 395 | |
| 396 | ) |
| 397 | strategy = DefaultStrategy({}) |
| 398 | strategy.analyze_ticker(ohlcv_history, {'pair': 'ETH/BTC'}) |
| 399 | assert ind_mock.call_count == 1 |
| 400 | assert buy_mock.call_count == 1 |
| 401 | assert buy_mock.call_count == 1 |
| 402 | |
| 403 | assert log_has('TA Analysis Launched', caplog) |
| 404 | assert not log_has('Skipping TA Analysis for already analyzed candle', caplog) |
| 405 | caplog.clear() |
| 406 | |
| 407 | strategy.analyze_ticker(ohlcv_history, {'pair': 'ETH/BTC'}) |
| 408 | # No analysis happens as process_only_new_candles is true |
| 409 | assert ind_mock.call_count == 2 |
| 410 | assert buy_mock.call_count == 2 |
| 411 | assert buy_mock.call_count == 2 |
| 412 | assert log_has('TA Analysis Launched', caplog) |
| 413 | assert not log_has('Skipping TA Analysis for already analyzed candle', caplog) |
| 414 | |
| 415 | |
| 416 | def test__analyze_ticker_internal_skip_analyze(ohlcv_history, mocker, caplog) -> None: |
| 417 | caplog.set_level(logging.DEBUG) |
| 418 | ind_mock = MagicMock(side_effect=lambda x, meta: x) |
| 419 | buy_mock = MagicMock(side_effect=lambda x, meta: x) |
| 420 | sell_mock = MagicMock(side_effect=lambda x, meta: x) |
| 421 | mocker.patch.multiple( |
| 422 | 'freqtrade.strategy.interface.IStrategy', |
| 423 | advise_indicators=ind_mock, |
| 424 | advise_buy=buy_mock, |
| 425 | advise_sell=sell_mock, |
| 426 | |
| 427 | ) |
| 428 | strategy = DefaultStrategy({}) |
| 429 | strategy.dp = DataProvider({}, None, None) |
| 430 | strategy.process_only_new_candles = True |
| 431 | |
| 432 | ret = strategy._analyze_ticker_internal(ohlcv_history, {'pair': 'ETH/BTC'}) |
| 433 | assert 'high' in ret.columns |
| 434 | assert 'low' in ret.columns |
| 435 | assert 'close' in ret.columns |
| 436 | assert isinstance(ret, DataFrame) |
| 437 | assert ind_mock.call_count == 1 |
| 438 | assert buy_mock.call_count == 1 |
| 439 | assert buy_mock.call_count == 1 |
| 440 | assert log_has('TA Analysis Launched', caplog) |
| 441 | assert not log_has('Skipping TA Analysis for already analyzed candle', caplog) |
| 442 | caplog.clear() |
| 443 | |
| 444 | ret = strategy._analyze_ticker_internal(ohlcv_history, {'pair': 'ETH/BTC'}) |
| 445 | # No analysis happens as process_only_new_candles is true |
| 446 | assert ind_mock.call_count == 1 |
| 447 | assert buy_mock.call_count == 1 |
| 448 | assert buy_mock.call_count == 1 |
| 449 | # only skipped analyze adds buy and sell columns, otherwise it's all mocked |
| 450 | assert 'buy' in ret.columns |
| 451 | assert 'sell' in ret.columns |
| 452 | assert ret['buy'].sum() == 0 |
| 453 | assert ret['sell'].sum() == 0 |
| 454 | assert not log_has('TA Analysis Launched', caplog) |
| 455 | assert log_has('Skipping TA Analysis for already analyzed candle', caplog) |
| 456 | |
| 457 | |
| 458 | @pytest.mark.usefixtures("init_persistence") |
| 459 | def test_is_pair_locked(default_conf): |
| 460 | default_conf.update({'strategy': 'DefaultStrategy'}) |
| 461 | PairLocks.timeframe = default_conf['timeframe'] |
| 462 | strategy = StrategyResolver.load_strategy(default_conf) |
| 463 | # No lock should be present |
| 464 | assert len(PairLocks.get_pair_locks(None)) == 0 |
| 465 | |
| 466 | pair = 'ETH/BTC' |
| 467 | assert not strategy.is_pair_locked(pair) |
| 468 | strategy.lock_pair(pair, arrow.now(timezone.utc).shift(minutes=4).datetime) |
| 469 | # ETH/BTC locked for 4 minutes |
| 470 | assert strategy.is_pair_locked(pair) |
| 471 | |
| 472 | # XRP/BTC should not be locked now |
| 473 | pair = 'XRP/BTC' |
| 474 | assert not strategy.is_pair_locked(pair) |
| 475 | |
| 476 | # Unlocking a pair that's not locked should not raise an error |
| 477 | strategy.unlock_pair(pair) |
| 478 | |
| 479 | # Unlock original pair |
| 480 | pair = 'ETH/BTC' |
| 481 | strategy.unlock_pair(pair) |
| 482 | assert not strategy.is_pair_locked(pair) |
| 483 | |
| 484 | pair = 'BTC/USDT' |
| 485 | # Lock until 14:30 |
| 486 | lock_time = datetime(2020, 5, 1, 14, 30, 0, tzinfo=timezone.utc) |
| 487 | # Subtract 2 seconds, as locking rounds up to the next candle. |
| 488 | strategy.lock_pair(pair, lock_time - timedelta(seconds=2)) |
| 489 | |
| 490 | assert not strategy.is_pair_locked(pair) |
| 491 | # latest candle is from 14:20, lock goes to 14:30 |
| 492 | assert strategy.is_pair_locked(pair, lock_time + timedelta(minutes=-10)) |
| 493 | assert strategy.is_pair_locked(pair, lock_time + timedelta(minutes=-50)) |
| 494 | |
| 495 | # latest candle is from 14:25 (lock should be lifted) |
| 496 | # Since this is the "new candle" available at 14:30 |
| 497 | assert not strategy.is_pair_locked(pair, lock_time + timedelta(minutes=-4)) |
| 498 | |
| 499 | # Should not be locked after time expired |
| 500 | assert not strategy.is_pair_locked(pair, lock_time + timedelta(minutes=10)) |
| 501 | |
| 502 | # Change timeframe to 15m |
| 503 | strategy.timeframe = '15m' |
| 504 | # Candle from 14:14 - lock goes until 14:30 |
| 505 | assert strategy.is_pair_locked(pair, lock_time + timedelta(minutes=-16)) |
| 506 | assert strategy.is_pair_locked(pair, lock_time + timedelta(minutes=-15, seconds=-2)) |
| 507 | # Candle from 14:15 - lock goes until 14:30 |
| 508 | assert not strategy.is_pair_locked(pair, lock_time + timedelta(minutes=-15)) |
| 509 | |
| 510 | |
| 511 | def test_is_informative_pairs_callback(default_conf): |
| 512 | default_conf.update({'strategy': 'TestStrategyLegacy'}) |
| 513 | strategy = StrategyResolver.load_strategy(default_conf) |
| 514 | # Should return empty |
| 515 | # Uses fallback to base implementation |
| 516 | assert [] == strategy.informative_pairs() |
| 517 | |
| 518 | |
| 519 | @pytest.mark.parametrize('error', [ |
| 520 | ValueError, KeyError, Exception, |
| 521 | ]) |
| 522 | def test_strategy_safe_wrapper_error(caplog, error): |
| 523 | def failing_method(): |
| 524 | raise error('This is an error.') |
| 525 | |
| 526 | def working_method(argumentpassedin): |
| 527 | return argumentpassedin |
| 528 | |
| 529 | with pytest.raises(StrategyError, match=r'This is an error.'): |
| 530 | strategy_safe_wrapper(failing_method, message='DeadBeef')() |
| 531 | |
| 532 | assert log_has_re(r'DeadBeef.*', caplog) |
| 533 | ret = strategy_safe_wrapper(failing_method, message='DeadBeef', default_retval=True)() |
| 534 | |
| 535 | assert isinstance(ret, bool) |
| 536 | assert ret |
| 537 | |
| 538 | caplog.clear() |
| 539 | # Test supressing error |
| 540 | ret = strategy_safe_wrapper(failing_method, message='DeadBeef', supress_error=True)() |
| 541 | assert log_has_re(r'DeadBeef.*', caplog) |
| 542 | |
| 543 | |
| 544 | @pytest.mark.parametrize('value', [ |
| 545 | 1, 22, 55, True, False, {'a': 1, 'b': '112'}, |
| 546 | [1, 2, 3, 4], (4, 2, 3, 6) |
| 547 | ]) |
| 548 | def test_strategy_safe_wrapper(value): |
| 549 | |
| 550 | def working_method(argumentpassedin): |
| 551 | return argumentpassedin |
| 552 | |
| 553 | ret = strategy_safe_wrapper(working_method, message='DeadBeef')(value) |
| 554 | |
| 555 | assert type(ret) == type(value) |
| 556 | assert ret == value |
| 557 | |
| 558 | |
| 559 | def test_hyperopt_parameters(): |
| 560 | from skopt.space import Categorical, Integer, Real |
| 561 | with pytest.raises(OperationalException, match=r"Name is determined.*"): |
| 562 | IntParameter(low=0, high=5, default=1, name='hello') |
| 563 | |
| 564 | with pytest.raises(OperationalException, match=r"IntParameter space must be.*"): |
| 565 | IntParameter(low=0, default=5, space='buy') |
| 566 | |
| 567 | with pytest.raises(OperationalException, match=r"RealParameter space must be.*"): |
| 568 | RealParameter(low=0, default=5, space='buy') |
| 569 | |
| 570 | with pytest.raises(OperationalException, match=r"DecimalParameter space must be.*"): |
| 571 | DecimalParameter(low=0, default=5, space='buy') |
| 572 | |
| 573 | with pytest.raises(OperationalException, match=r"IntParameter space invalid\."): |
| 574 | IntParameter([0, 10], high=7, default=5, space='buy') |
| 575 | |
| 576 | with pytest.raises(OperationalException, match=r"RealParameter space invalid\."): |
| 577 | RealParameter([0, 10], high=7, default=5, space='buy') |
| 578 | |
| 579 | with pytest.raises(OperationalException, match=r"DecimalParameter space invalid\."): |
| 580 | DecimalParameter([0, 10], high=7, default=5, space='buy') |
| 581 | |
| 582 | with pytest.raises(OperationalException, match=r"CategoricalParameter space must.*"): |
| 583 | CategoricalParameter(['aa'], default='aa', space='buy') |
| 584 | |
| 585 | with pytest.raises(TypeError): |
| 586 | BaseParameter(opt_range=[0, 1], default=1, space='buy') |
| 587 | |
| 588 | intpar = IntParameter(low=0, high=5, default=1, space='buy') |
| 589 | assert intpar.value == 1 |
| 590 | assert isinstance(intpar.get_space(''), Integer) |
| 591 | |
| 592 | fltpar = RealParameter(low=0.0, high=5.5, default=1.0, space='buy') |
| 593 | assert isinstance(fltpar.get_space(''), Real) |
| 594 | assert fltpar.value == 1 |
| 595 | |
| 596 | fltpar = DecimalParameter(low=0.0, high=5.5, default=1.0004, decimals=3, space='buy') |
| 597 | assert isinstance(fltpar.get_space(''), Integer) |
| 598 | assert fltpar.value == 1 |
| 599 | |
| 600 | catpar = CategoricalParameter(['buy_rsi', 'buy_macd', 'buy_none'], |
| 601 | default='buy_macd', space='buy') |
| 602 | assert isinstance(catpar.get_space(''), Categorical) |
| 603 | assert catpar.value == 'buy_macd' |
| 604 | |
| 605 | |
| 606 | def test_auto_hyperopt_interface(default_conf): |
| 607 | default_conf.update({'strategy': 'HyperoptableStrategy'}) |
| 608 | PairLocks.timeframe = default_conf['timeframe'] |
| 609 | strategy = StrategyResolver.load_strategy(default_conf) |
| 610 | |
| 611 | assert strategy.buy_rsi.value == strategy.buy_params['buy_rsi'] |
| 612 | # PlusDI is NOT in the buy-params, so default should be used |
| 613 | assert strategy.buy_plusdi.value == 0.5 |
| 614 | assert strategy.sell_rsi.value == strategy.sell_params['sell_rsi'] |
| 615 | |
| 616 | # Parameter is disabled - so value from sell_param dict will NOT be used. |
| 617 | assert strategy.sell_minusdi.value == 0.5 |
| 618 | |
| 619 | strategy.sell_rsi = IntParameter([0, 10], default=5, space='buy') |
| 620 | |
| 621 | with pytest.raises(OperationalException, match=r"Inconclusive parameter.*"): |
| 622 | [x for x in strategy.enumerate_parameters('sell')] |