freqtrade_origin/freqtrade/plugins/protections/stoploss_guard.py

92 lines
3.6 KiB
Python
Raw Normal View History

2020-10-14 05:40:44 +00:00
import logging
from datetime import datetime, timedelta
from typing import Any, Dict, Optional
2020-10-14 05:40:44 +00:00
2022-09-18 11:20:36 +00:00
from freqtrade.constants import Config, LongShort
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
2022-09-18 11:20:36 +00:00
def __init__(self, config: Config, protection_config: Dict[str, Any]) -> None:
2020-10-14 05:40:44 +00:00
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)
self._only_per_side = protection_config.get('only_per_side', False)
self._profit_limit = protection_config.get('required_profit', 0.0)
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 "
f"with profit < {self._profit_limit:.2%} 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.')
def _stoploss_guard(self, date_now: datetime, pair: Optional[str],
side: LongShort) -> Optional[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
trades1 = Trade.get_trades_proxy(pair=pair, is_open=False, close_date=look_back_until)
2022-03-24 19:33:47 +00:00
trades = [trade for trade in trades1 if (str(trade.exit_reason) in (
2022-03-25 05:55:37 +00:00
ExitType.TRAILING_STOP_LOSS.value, ExitType.STOP_LOSS.value,
ExitType.STOPLOSS_ON_EXCHANGE.value, ExitType.LIQUIDATION.value)
and trade.close_profit and trade.close_profit < self._profit_limit)]
2020-10-14 05:40:44 +00:00
2022-04-24 12:43:30 +00:00
if self._only_per_side:
# Long or short trades only
trades = [trade for trade in trades if trade.trade_direction == side]
if len(trades) < self._trade_limit:
2022-04-24 08:29:19 +00:00
return 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)
2022-04-24 08:29:19 +00:00
return ProtectionReturn(
lock=True,
until=until,
reason=self._reason(),
2022-04-24 09:23:26 +00:00
lock_side=(side if self._only_per_side else '*')
2022-04-24 08:29:19 +00:00
)
2022-04-24 08:58:21 +00:00
def global_stop(self, date_now: datetime, side: LongShort) -> Optional[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:
2022-04-24 08:29:19 +00:00
return None
return self._stoploss_guard(date_now, None, side)
2020-10-24 14:52:26 +00:00
2022-04-24 08:58:21 +00:00
def stop_per_pair(
self, pair: str, date_now: datetime, side: LongShort) -> Optional[ProtectionReturn]:
2020-10-24 14:52:26 +00:00
"""
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, side)