| 1 | import random |
| 2 | from datetime import datetime, timedelta |
| 3 | |
| 4 | import pytest |
| 5 | |
| 6 | from freqtrade import constants |
| 7 | from freqtrade.persistence import PairLocks, Trade |
| 8 | from freqtrade.plugins.protectionmanager import ProtectionManager |
| 9 | from freqtrade.strategy.interface import SellType |
| 10 | from tests.conftest import get_patched_freqtradebot, log_has_re |
| 11 | |
| 12 | |
| 13 | def generate_mock_trade(pair: str, fee: float, is_open: bool, |
| 14 | sell_reason: str = SellType.SELL_SIGNAL, |
| 15 | min_ago_open: int = None, min_ago_close: int = None, |
| 16 | profit_rate: float = 0.9 |
| 17 | ): |
| 18 | open_rate = random.random() |
| 19 | |
| 20 | trade = Trade( |
| 21 | pair=pair, |
| 22 | stake_amount=0.01, |
| 23 | fee_open=fee, |
| 24 | fee_close=fee, |
| 25 | open_date=datetime.utcnow() - timedelta(minutes=min_ago_open or 200), |
| 26 | close_date=datetime.utcnow() - timedelta(minutes=min_ago_close or 30), |
| 27 | open_rate=open_rate, |
| 28 | is_open=is_open, |
| 29 | amount=0.01 / open_rate, |
| 30 | exchange='binance', |
| 31 | ) |
| 32 | trade.recalc_open_trade_value() |
| 33 | if not is_open: |
| 34 | trade.close(open_rate * profit_rate) |
| 35 | trade.sell_reason = sell_reason |
| 36 | |
| 37 | return trade |
| 38 | |
| 39 | |
| 40 | def test_protectionmanager(mocker, default_conf): |
| 41 | default_conf['protections'] = [{'method': protection} |
| 42 | for protection in constants.AVAILABLE_PROTECTIONS] |
| 43 | freqtrade = get_patched_freqtradebot(mocker, default_conf) |
| 44 | |
| 45 | for handler in freqtrade.protections._protection_handlers: |
| 46 | assert handler.name in constants.AVAILABLE_PROTECTIONS |
| 47 | if not handler.has_global_stop: |
| 48 | assert handler.global_stop(datetime.utcnow()) == (False, None, None) |
| 49 | if not handler.has_local_stop: |
| 50 | assert handler.stop_per_pair('XRP/BTC', datetime.utcnow()) == (False, None, None) |
| 51 | |
| 52 | |
| 53 | @pytest.mark.parametrize('timeframe,expected,protconf', [ |
| 54 | ('1m', [20, 10], |
| 55 | [{"method": "StoplossGuard", "lookback_period_candles": 20, "stop_duration": 10}]), |
| 56 | ('5m', [100, 15], |
| 57 | [{"method": "StoplossGuard", "lookback_period_candles": 20, "stop_duration": 15}]), |
| 58 | ('1h', [1200, 40], |
| 59 | [{"method": "StoplossGuard", "lookback_period_candles": 20, "stop_duration": 40}]), |
| 60 | ('1d', [1440, 5], |
| 61 | [{"method": "StoplossGuard", "lookback_period_candles": 1, "stop_duration": 5}]), |
| 62 | ('1m', [20, 5], |
| 63 | [{"method": "StoplossGuard", "lookback_period": 20, "stop_duration_candles": 5}]), |
| 64 | ('5m', [15, 25], |
| 65 | [{"method": "StoplossGuard", "lookback_period": 15, "stop_duration_candles": 5}]), |
| 66 | ('1h', [50, 600], |
| 67 | [{"method": "StoplossGuard", "lookback_period": 50, "stop_duration_candles": 10}]), |
| 68 | ('1h', [60, 540], |
| 69 | [{"method": "StoplossGuard", "lookback_period_candles": 1, "stop_duration_candles": 9}]), |
| 70 | ]) |
| 71 | def test_protections_init(mocker, default_conf, timeframe, expected, protconf): |
| 72 | default_conf['timeframe'] = timeframe |
| 73 | default_conf['protections'] = protconf |
| 74 | man = ProtectionManager(default_conf) |
| 75 | assert len(man._protection_handlers) == len(protconf) |
| 76 | assert man._protection_handlers[0]._lookback_period == expected[0] |
| 77 | assert man._protection_handlers[0]._stop_duration == expected[1] |
| 78 | |
| 79 | |
| 80 | @pytest.mark.usefixtures("init_persistence") |
| 81 | def test_stoploss_guard(mocker, default_conf, fee, caplog): |
| 82 | default_conf['protections'] = [{ |
| 83 | "method": "StoplossGuard", |
| 84 | "lookback_period": 60, |
| 85 | "stop_duration": 40, |
| 86 | "trade_limit": 3 |
| 87 | }] |
| 88 | freqtrade = get_patched_freqtradebot(mocker, default_conf) |
| 89 | message = r"Trading stopped due to .*" |
| 90 | assert not freqtrade.protections.global_stop() |
| 91 | assert not log_has_re(message, caplog) |
| 92 | caplog.clear() |
| 93 | |
| 94 | Trade.query.session.add(generate_mock_trade( |
| 95 | 'XRP/BTC', fee.return_value, False, sell_reason=SellType.STOP_LOSS.value, |
| 96 | min_ago_open=200, min_ago_close=30, |
| 97 | )) |
| 98 | |
| 99 | assert not freqtrade.protections.global_stop() |
| 100 | assert not log_has_re(message, caplog) |
| 101 | caplog.clear() |
| 102 | # This trade does not count, as it's closed too long ago |
| 103 | Trade.query.session.add(generate_mock_trade( |
| 104 | 'BCH/BTC', fee.return_value, False, sell_reason=SellType.STOP_LOSS.value, |
| 105 | min_ago_open=250, min_ago_close=100, |
| 106 | )) |
| 107 | |
| 108 | Trade.query.session.add(generate_mock_trade( |
| 109 | 'ETH/BTC', fee.return_value, False, sell_reason=SellType.STOP_LOSS.value, |
| 110 | min_ago_open=240, min_ago_close=30, |
| 111 | )) |
| 112 | # 3 Trades closed - but the 2nd has been closed too long ago. |
| 113 | assert not freqtrade.protections.global_stop() |
| 114 | assert not log_has_re(message, caplog) |
| 115 | caplog.clear() |
| 116 | |
| 117 | Trade.query.session.add(generate_mock_trade( |
| 118 | 'LTC/BTC', fee.return_value, False, sell_reason=SellType.STOP_LOSS.value, |
| 119 | min_ago_open=180, min_ago_close=30, |
| 120 | )) |
| 121 | |
| 122 | assert freqtrade.protections.global_stop() |
| 123 | assert log_has_re(message, caplog) |
| 124 | assert PairLocks.is_global_lock() |
| 125 | |
| 126 | # Test 5m after lock-period - this should try and relock the pair, but end-time |
| 127 | # should be the previous end-time |
| 128 | end_time = PairLocks.get_pair_longest_lock('*').lock_end_time + timedelta(minutes=5) |
| 129 | assert freqtrade.protections.global_stop(end_time) |
| 130 | assert not PairLocks.is_global_lock(end_time) |
| 131 | |
| 132 | |
| 133 | @pytest.mark.parametrize('only_per_pair', [False, True]) |
| 134 | @pytest.mark.usefixtures("init_persistence") |
| 135 | def test_stoploss_guard_perpair(mocker, default_conf, fee, caplog, only_per_pair): |
| 136 | default_conf['protections'] = [{ |
| 137 | "method": "StoplossGuard", |
| 138 | "lookback_period": 60, |
| 139 | "trade_limit": 2, |
| 140 | "stop_duration": 60, |
| 141 | "only_per_pair": only_per_pair |
| 142 | }] |
| 143 | freqtrade = get_patched_freqtradebot(mocker, default_conf) |
| 144 | message = r"Trading stopped due to .*" |
| 145 | pair = 'XRP/BTC' |
| 146 | assert not freqtrade.protections.stop_per_pair(pair) |
| 147 | assert not freqtrade.protections.global_stop() |
| 148 | assert not log_has_re(message, caplog) |
| 149 | caplog.clear() |
| 150 | |
| 151 | Trade.query.session.add(generate_mock_trade( |
| 152 | pair, fee.return_value, False, sell_reason=SellType.STOP_LOSS.value, |
| 153 | min_ago_open=200, min_ago_close=30, profit_rate=0.9, |
| 154 | )) |
| 155 | |
| 156 | assert not freqtrade.protections.stop_per_pair(pair) |
| 157 | assert not freqtrade.protections.global_stop() |
| 158 | assert not log_has_re(message, caplog) |
| 159 | caplog.clear() |
| 160 | # This trade does not count, as it's closed too long ago |
| 161 | Trade.query.session.add(generate_mock_trade( |
| 162 | pair, fee.return_value, False, sell_reason=SellType.STOP_LOSS.value, |
| 163 | min_ago_open=250, min_ago_close=100, profit_rate=0.9, |
| 164 | )) |
| 165 | # Trade does not count for per pair stop as it's the wrong pair. |
| 166 | Trade.query.session.add(generate_mock_trade( |
| 167 | 'ETH/BTC', fee.return_value, False, sell_reason=SellType.STOP_LOSS.value, |
| 168 | min_ago_open=240, min_ago_close=30, profit_rate=0.9, |
| 169 | )) |
| 170 | # 3 Trades closed - but the 2nd has been closed too long ago. |
| 171 | assert not freqtrade.protections.stop_per_pair(pair) |
| 172 | assert freqtrade.protections.global_stop() != only_per_pair |
| 173 | if not only_per_pair: |
| 174 | assert log_has_re(message, caplog) |
| 175 | else: |
| 176 | assert not log_has_re(message, caplog) |
| 177 | |
| 178 | caplog.clear() |
| 179 | |
| 180 | # 2nd Trade that counts with correct pair |
| 181 | Trade.query.session.add(generate_mock_trade( |
| 182 | pair, fee.return_value, False, sell_reason=SellType.STOP_LOSS.value, |
| 183 | min_ago_open=180, min_ago_close=30, profit_rate=0.9, |
| 184 | )) |
| 185 | |
| 186 | assert freqtrade.protections.stop_per_pair(pair) |
| 187 | assert freqtrade.protections.global_stop() != only_per_pair |
| 188 | assert PairLocks.is_pair_locked(pair) |
| 189 | assert PairLocks.is_global_lock() != only_per_pair |
| 190 | |
| 191 | |
| 192 | @pytest.mark.usefixtures("init_persistence") |
| 193 | def test_CooldownPeriod(mocker, default_conf, fee, caplog): |
| 194 | default_conf['protections'] = [{ |
| 195 | "method": "CooldownPeriod", |
| 196 | "stop_duration": 60, |
| 197 | }] |
| 198 | freqtrade = get_patched_freqtradebot(mocker, default_conf) |
| 199 | message = r"Trading stopped due to .*" |
| 200 | assert not freqtrade.protections.global_stop() |
| 201 | assert not freqtrade.protections.stop_per_pair('XRP/BTC') |
| 202 | |
| 203 | assert not log_has_re(message, caplog) |
| 204 | caplog.clear() |
| 205 | |
| 206 | Trade.query.session.add(generate_mock_trade( |
| 207 | 'XRP/BTC', fee.return_value, False, sell_reason=SellType.STOP_LOSS.value, |
| 208 | min_ago_open=200, min_ago_close=30, |
| 209 | )) |
| 210 | |
| 211 | assert not freqtrade.protections.global_stop() |
| 212 | assert freqtrade.protections.stop_per_pair('XRP/BTC') |
| 213 | assert PairLocks.is_pair_locked('XRP/BTC') |
| 214 | assert not PairLocks.is_global_lock() |
| 215 | |
| 216 | Trade.query.session.add(generate_mock_trade( |
| 217 | 'ETH/BTC', fee.return_value, False, sell_reason=SellType.ROI.value, |
| 218 | min_ago_open=205, min_ago_close=35, |
| 219 | )) |
| 220 | |
| 221 | assert not freqtrade.protections.global_stop() |
| 222 | assert not PairLocks.is_pair_locked('ETH/BTC') |
| 223 | assert freqtrade.protections.stop_per_pair('ETH/BTC') |
| 224 | assert PairLocks.is_pair_locked('ETH/BTC') |
| 225 | assert not PairLocks.is_global_lock() |
| 226 | |
| 227 | |
| 228 | @pytest.mark.usefixtures("init_persistence") |
| 229 | def test_LowProfitPairs(mocker, default_conf, fee, caplog): |
| 230 | default_conf['protections'] = [{ |
| 231 | "method": "LowProfitPairs", |
| 232 | "lookback_period": 400, |
| 233 | "stop_duration": 60, |
| 234 | "trade_limit": 2, |
| 235 | "required_profit": 0.0, |
| 236 | }] |
| 237 | freqtrade = get_patched_freqtradebot(mocker, default_conf) |
| 238 | message = r"Trading stopped due to .*" |
| 239 | assert not freqtrade.protections.global_stop() |
| 240 | assert not freqtrade.protections.stop_per_pair('XRP/BTC') |
| 241 | |
| 242 | assert not log_has_re(message, caplog) |
| 243 | caplog.clear() |
| 244 | |
| 245 | Trade.query.session.add(generate_mock_trade( |
| 246 | 'XRP/BTC', fee.return_value, False, sell_reason=SellType.STOP_LOSS.value, |
| 247 | min_ago_open=800, min_ago_close=450, profit_rate=0.9, |
| 248 | )) |
| 249 | |
| 250 | # Not locked with 1 trade |
| 251 | assert not freqtrade.protections.global_stop() |
| 252 | assert not freqtrade.protections.stop_per_pair('XRP/BTC') |
| 253 | assert not PairLocks.is_pair_locked('XRP/BTC') |
| 254 | assert not PairLocks.is_global_lock() |
| 255 | |
| 256 | Trade.query.session.add(generate_mock_trade( |
| 257 | 'XRP/BTC', fee.return_value, False, sell_reason=SellType.STOP_LOSS.value, |
| 258 | min_ago_open=200, min_ago_close=120, profit_rate=0.9, |
| 259 | )) |
| 260 | |
| 261 | # Not locked with 1 trade (first trade is outside of lookback_period) |
| 262 | assert not freqtrade.protections.global_stop() |
| 263 | assert not freqtrade.protections.stop_per_pair('XRP/BTC') |
| 264 | assert not PairLocks.is_pair_locked('XRP/BTC') |
| 265 | assert not PairLocks.is_global_lock() |
| 266 | |
| 267 | # Add positive trade |
| 268 | Trade.query.session.add(generate_mock_trade( |
| 269 | 'XRP/BTC', fee.return_value, False, sell_reason=SellType.ROI.value, |
| 270 | min_ago_open=20, min_ago_close=10, profit_rate=1.15, |
| 271 | )) |
| 272 | assert not freqtrade.protections.stop_per_pair('XRP/BTC') |
| 273 | assert not PairLocks.is_pair_locked('XRP/BTC') |
| 274 | |
| 275 | Trade.query.session.add(generate_mock_trade( |
| 276 | 'XRP/BTC', fee.return_value, False, sell_reason=SellType.STOP_LOSS.value, |
| 277 | min_ago_open=110, min_ago_close=20, profit_rate=0.8, |
| 278 | )) |
| 279 | |
| 280 | # Locks due to 2nd trade |
| 281 | assert not freqtrade.protections.global_stop() |
| 282 | assert freqtrade.protections.stop_per_pair('XRP/BTC') |
| 283 | assert PairLocks.is_pair_locked('XRP/BTC') |
| 284 | assert not PairLocks.is_global_lock() |
| 285 | |
| 286 | |
| 287 | @pytest.mark.usefixtures("init_persistence") |
| 288 | def test_MaxDrawdown(mocker, default_conf, fee, caplog): |
| 289 | default_conf['protections'] = [{ |
| 290 | "method": "MaxDrawdown", |
| 291 | "lookback_period": 1000, |
| 292 | "stop_duration": 60, |
| 293 | "trade_limit": 3, |
| 294 | "max_allowed_drawdown": 0.15 |
| 295 | }] |
| 296 | freqtrade = get_patched_freqtradebot(mocker, default_conf) |
| 297 | message = r"Trading stopped due to Max.*" |
| 298 | |
| 299 | assert not freqtrade.protections.global_stop() |
| 300 | assert not freqtrade.protections.stop_per_pair('XRP/BTC') |
| 301 | caplog.clear() |
| 302 | |
| 303 | Trade.query.session.add(generate_mock_trade( |
| 304 | 'XRP/BTC', fee.return_value, False, sell_reason=SellType.STOP_LOSS.value, |
| 305 | min_ago_open=1000, min_ago_close=900, profit_rate=1.1, |
| 306 | )) |
| 307 | Trade.query.session.add(generate_mock_trade( |
| 308 | 'ETH/BTC', fee.return_value, False, sell_reason=SellType.STOP_LOSS.value, |
| 309 | min_ago_open=1000, min_ago_close=900, profit_rate=1.1, |
| 310 | )) |
| 311 | Trade.query.session.add(generate_mock_trade( |
| 312 | 'NEO/BTC', fee.return_value, False, sell_reason=SellType.STOP_LOSS.value, |
| 313 | min_ago_open=1000, min_ago_close=900, profit_rate=1.1, |
| 314 | )) |
| 315 | # No losing trade yet ... so max_drawdown will raise exception |
| 316 | assert not freqtrade.protections.global_stop() |
| 317 | assert not freqtrade.protections.stop_per_pair('XRP/BTC') |
| 318 | |
| 319 | Trade.query.session.add(generate_mock_trade( |
| 320 | 'XRP/BTC', fee.return_value, False, sell_reason=SellType.STOP_LOSS.value, |
| 321 | min_ago_open=500, min_ago_close=400, profit_rate=0.9, |
| 322 | )) |
| 323 | # Not locked with one trade |
| 324 | assert not freqtrade.protections.global_stop() |
| 325 | assert not freqtrade.protections.stop_per_pair('XRP/BTC') |
| 326 | assert not PairLocks.is_pair_locked('XRP/BTC') |
| 327 | assert not PairLocks.is_global_lock() |
| 328 | |
| 329 | Trade.query.session.add(generate_mock_trade( |
| 330 | 'XRP/BTC', fee.return_value, False, sell_reason=SellType.STOP_LOSS.value, |
| 331 | min_ago_open=1200, min_ago_close=1100, profit_rate=0.5, |
| 332 | )) |
| 333 | |
| 334 | # Not locked with 1 trade (2nd trade is outside of lookback_period) |
| 335 | assert not freqtrade.protections.global_stop() |
| 336 | assert not freqtrade.protections.stop_per_pair('XRP/BTC') |
| 337 | assert not PairLocks.is_pair_locked('XRP/BTC') |
| 338 | assert not PairLocks.is_global_lock() |
| 339 | assert not log_has_re(message, caplog) |
| 340 | |
| 341 | # Winning trade ... (should not lock, does not change drawdown!) |
| 342 | Trade.query.session.add(generate_mock_trade( |
| 343 | 'XRP/BTC', fee.return_value, False, sell_reason=SellType.ROI.value, |
| 344 | min_ago_open=320, min_ago_close=410, profit_rate=1.5, |
| 345 | )) |
| 346 | assert not freqtrade.protections.global_stop() |
| 347 | assert not PairLocks.is_global_lock() |
| 348 | |
| 349 | caplog.clear() |
| 350 | |
| 351 | # Add additional negative trade, causing a loss of > 15% |
| 352 | Trade.query.session.add(generate_mock_trade( |
| 353 | 'XRP/BTC', fee.return_value, False, sell_reason=SellType.ROI.value, |
| 354 | min_ago_open=20, min_ago_close=10, profit_rate=0.8, |
| 355 | )) |
| 356 | assert not freqtrade.protections.stop_per_pair('XRP/BTC') |
| 357 | # local lock not supported |
| 358 | assert not PairLocks.is_pair_locked('XRP/BTC') |
| 359 | assert freqtrade.protections.global_stop() |
| 360 | assert PairLocks.is_global_lock() |
| 361 | assert log_has_re(message, caplog) |
| 362 | |
| 363 | |
| 364 | @pytest.mark.parametrize("protectionconf,desc_expected,exception_expected", [ |
| 365 | ({"method": "StoplossGuard", "lookback_period": 60, "trade_limit": 2, "stop_duration": 60}, |
| 366 | "[{'StoplossGuard': 'StoplossGuard - Frequent Stoploss Guard, " |
| 367 | "2 stoplosses within 60 minutes.'}]", |
| 368 | None |
| 369 | ), |
| 370 | ({"method": "CooldownPeriod", "stop_duration": 60}, |
| 371 | "[{'CooldownPeriod': 'CooldownPeriod - Cooldown period of 60 minutes.'}]", |
| 372 | None |
| 373 | ), |
| 374 | ({"method": "LowProfitPairs", "lookback_period": 60, "stop_duration": 60}, |
| 375 | "[{'LowProfitPairs': 'LowProfitPairs - Low Profit Protection, locks pairs with " |
| 376 | "profit < 0.0 within 60 minutes.'}]", |
| 377 | None |
| 378 | ), |
| 379 | ({"method": "MaxDrawdown", "lookback_period": 60, "stop_duration": 60}, |
| 380 | "[{'MaxDrawdown': 'MaxDrawdown - Max drawdown protection, stop trading if drawdown is > 0.0 " |
| 381 | "within 60 minutes.'}]", |
| 382 | None |
| 383 | ), |
| 384 | ({"method": "StoplossGuard", "lookback_period_candles": 12, "trade_limit": 2, |
| 385 | "stop_duration": 60}, |
| 386 | "[{'StoplossGuard': 'StoplossGuard - Frequent Stoploss Guard, " |
| 387 | "2 stoplosses within 12 candles.'}]", |
| 388 | None |
| 389 | ), |
| 390 | ({"method": "CooldownPeriod", "stop_duration_candles": 5}, |
| 391 | "[{'CooldownPeriod': 'CooldownPeriod - Cooldown period of 5 candles.'}]", |
| 392 | None |
| 393 | ), |
| 394 | ({"method": "LowProfitPairs", "lookback_period_candles": 11, "stop_duration": 60}, |
| 395 | "[{'LowProfitPairs': 'LowProfitPairs - Low Profit Protection, locks pairs with " |
| 396 | "profit < 0.0 within 11 candles.'}]", |
| 397 | None |
| 398 | ), |
| 399 | ({"method": "MaxDrawdown", "lookback_period_candles": 20, "stop_duration": 60}, |
| 400 | "[{'MaxDrawdown': 'MaxDrawdown - Max drawdown protection, stop trading if drawdown is > 0.0 " |
| 401 | "within 20 candles.'}]", |
| 402 | None |
| 403 | ), |
| 404 | ]) |
| 405 | def test_protection_manager_desc(mocker, default_conf, protectionconf, |
| 406 | desc_expected, exception_expected): |
| 407 | |
| 408 | default_conf['protections'] = [protectionconf] |
| 409 | freqtrade = get_patched_freqtradebot(mocker, default_conf) |
| 410 | |
| 411 | short_desc = str(freqtrade.protections.short_desc()) |
| 412 | assert short_desc == desc_expected |