freqtrade_origin/freqtrade/plugins/protections/stoploss_guard.py

80 lines
3.0 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
2020-10-15 05:38:00 +00:00
from sqlalchemy import and_, or_
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
from freqtrade.strategy.interface import SellType
logger = logging.getLogger(__name__)
class StoplossGuard(IProtection):
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._lookback_period = protection_config.get('lookback_period', 60)
self._trade_limit = protection_config.get('trade_limit', 10)
2020-11-11 06:48:27 +00:00
self._stop_duration = protection_config.get('stop_duration', 60)
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"within {self._lookback_period} minutes.")
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)
filters = [
Trade.is_open.is_(False),
Trade.close_date > look_back_until,
or_(Trade.sell_reason == SellType.STOP_LOSS.value,
and_(Trade.sell_reason == SellType.TRAILING_STOP_LOSS.value,
Trade.close_profit < 0))
]
if pair:
filters.append(Trade.pair == pair)
trades = Trade.get_trades(filters).all()
2020-10-15 05:38:00 +00:00
if len(trades) > self._trade_limit:
2020-11-19 18:45:22 +00:00
self.log_once(logger.info, f"Trading stopped due to {self._trade_limit} "
f"stoplosses within {self._lookback_period} minutes.")
until = self.calculate_lock_end(trades, self._stop_duration)
2020-10-15 06:07:09 +00:00
return True, until, self._reason()
2020-10-14 05:40:44 +00:00
2020-10-15 06:07:09 +00:00
return False, None, None
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
"""
return self._stoploss_guard(date_now, pair=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 False, None, None