stable/freqtrade/plugins/protections/stoploss_guard.py

88 lines
3.3 KiB
Python
Raw Normal View History

2020-10-14 05:40:44 +00:00
import logging
from datetime import datetime, timedelta
2020-10-24 14:52:26 +00:00
from typing import Any, Dict
2020-10-14 05:40:44 +00:00
2022-03-25 05:55:37 +00:00
from freqtrade.enums import ExitType
2020-10-14 05:40:44 +00:00
from freqtrade.persistence import Trade
2020-10-15 06:07:09 +00:00
from freqtrade.plugins.protections import IProtection, ProtectionReturn
2020-10-14 05:40:44 +00:00
logger = logging.getLogger(__name__)
class StoplossGuard(IProtection):
has_global_stop: bool = True
has_local_stop: bool = True
2020-10-14 05:40:44 +00:00
def __init__(self, config: Dict[str, Any], protection_config: Dict[str, Any]) -> None:
super().__init__(config, protection_config)
2020-10-15 06:07:09 +00:00
2020-10-14 05:40:44 +00:00
self._trade_limit = protection_config.get('trade_limit', 10)
2020-11-25 10:11:55 +00:00
self._disable_global_stop = protection_config.get('only_per_pair', False)
2020-10-14 05:40:44 +00:00
def short_desc(self) -> str:
"""
Short method description - used for startup-messages
"""
2020-10-15 06:07:09 +00:00
return (f"{self.name} - Frequent Stoploss Guard, {self._trade_limit} stoplosses "
2020-12-07 10:08:54 +00:00
f"within {self.lookback_period_str}.")
2020-10-14 05:40:44 +00:00
2020-11-11 06:48:27 +00:00
def _reason(self) -> str:
"""
LockReason to use
"""
return (f'{self._trade_limit} stoplosses in {self._lookback_period} min, '
f'locking for {self._stop_duration} min.')
2020-10-15 06:07:09 +00:00
def _stoploss_guard(self, date_now: datetime, pair: str = None) -> ProtectionReturn:
2020-10-14 05:40:44 +00:00
"""
Evaluate recent trades
"""
look_back_until = date_now - timedelta(minutes=self._lookback_period)
2020-11-16 19:09:34 +00:00
# filters = [
# Trade.is_open.is_(False),
# Trade.close_date > look_back_until,
2022-03-25 05:55:37 +00:00
# or_(Trade.sell_reason == ExitType.STOP_LOSS.value,
# and_(Trade.sell_reason == ExitType.TRAILING_STOP_LOSS.value,
2020-11-16 19:09:34 +00:00
# Trade.close_profit < 0))
# ]
# if pair:
# filters.append(Trade.pair == pair)
# trades = Trade.get_trades(filters).all()
trades1 = Trade.get_trades_proxy(pair=pair, is_open=False, close_date=look_back_until)
trades = [trade for trade in trades1 if (str(trade.sell_reason) in (
2022-03-25 05:55:37 +00:00
ExitType.TRAILING_STOP_LOSS.value, ExitType.STOP_LOSS.value,
ExitType.STOPLOSS_ON_EXCHANGE.value)
2021-08-06 22:19:36 +00:00
and trade.close_profit and trade.close_profit < 0)]
2020-10-14 05:40:44 +00:00
if len(trades) < self._trade_limit:
return False, None, None
2020-10-14 05:40:44 +00:00
self.log_once(f"Trading stopped due to {self._trade_limit} "
f"stoplosses within {self._lookback_period} minutes.", logger.info)
until = self.calculate_lock_end(trades, self._stop_duration)
return True, until, self._reason()
2020-10-14 05:40:44 +00:00
2020-10-15 06:07:09 +00:00
def global_stop(self, date_now: datetime) -> ProtectionReturn:
2020-10-14 05:40:44 +00:00
"""
Stops trading (position entering) for all pairs
This must evaluate to true for the whole period of the "cooldown period".
2020-10-15 06:07:09 +00:00
:return: Tuple of [bool, until, reason].
If true, all pairs will be locked with <reason> until <until>
2020-10-14 05:40:44 +00:00
"""
2020-11-25 10:11:55 +00:00
if self._disable_global_stop:
return False, None, None
return self._stoploss_guard(date_now, None)
2020-10-24 14:52:26 +00:00
def stop_per_pair(self, pair: str, date_now: datetime) -> ProtectionReturn:
"""
Stops trading (position entering) for this pair
This must evaluate to true for the whole period of the "cooldown period".
:return: Tuple of [bool, until, reason].
If true, this pair will be locked with <reason> until <until>
"""
return self._stoploss_guard(date_now, pair)