stable/freqtrade/plugins/protections/max_drawdown_protection.py

96 lines
3.5 KiB
Python
Raw Normal View History

2020-11-30 07:05:48 +00:00
import logging
from datetime import datetime, timedelta
2022-04-24 08:29:19 +00:00
from typing import Any, Dict, Optional
2020-11-30 07:05:48 +00:00
import pandas as pd
2022-04-24 08:58:21 +00:00
from freqtrade.constants import LongShort
2020-11-30 07:05:48 +00:00
from freqtrade.data.btanalysis import calculate_max_drawdown
from freqtrade.persistence import Trade
from freqtrade.plugins.protections import IProtection, ProtectionReturn
logger = logging.getLogger(__name__)
class MaxDrawdown(IProtection):
has_global_stop: bool = True
has_local_stop: bool = False
def __init__(self, config: Dict[str, Any], protection_config: Dict[str, Any]) -> None:
super().__init__(config, protection_config)
self._trade_limit = protection_config.get('trade_limit', 1)
self._max_allowed_drawdown = protection_config.get('max_allowed_drawdown', 0.0)
# TODO: Implement checks to limit max_drawdown to sensible values
def short_desc(self) -> str:
"""
Short method description - used for startup-messages
"""
return (f"{self.name} - Max drawdown protection, stop trading if drawdown is > "
2020-12-07 10:08:54 +00:00
f"{self._max_allowed_drawdown} within {self.lookback_period_str}.")
2020-11-30 07:05:48 +00:00
def _reason(self, drawdown: float) -> str:
"""
LockReason to use
"""
2021-12-31 12:49:21 +00:00
return (f'{drawdown} passed {self._max_allowed_drawdown} in {self.lookback_period_str}, '
2020-12-07 10:08:54 +00:00
f'locking for {self.stop_duration_str}.')
2020-11-30 07:05:48 +00:00
2022-04-24 08:29:19 +00:00
def _max_drawdown(self, date_now: datetime) -> Optional[ProtectionReturn]:
2020-11-30 07:05:48 +00:00
"""
Evaluate recent trades for drawdown ...
"""
look_back_until = date_now - timedelta(minutes=self._lookback_period)
2020-11-16 19:09:34 +00:00
trades = Trade.get_trades_proxy(is_open=False, close_date=look_back_until)
2020-11-30 07:05:48 +00:00
2020-11-30 18:07:39 +00:00
trades_df = pd.DataFrame([trade.to_json() for trade in trades])
2020-11-30 07:05:48 +00:00
if len(trades) < self._trade_limit:
# Not enough trades in the relevant period
2022-04-24 08:29:19 +00:00
return None
2020-11-30 07:05:48 +00:00
# Drawdown is always positive
2020-12-07 14:45:02 +00:00
try:
# TODO: This should use absolute profit calculation, considering account balance.
drawdown, _, _, _, _, _ = calculate_max_drawdown(trades_df, value_col='close_profit')
2020-12-07 14:45:02 +00:00
except ValueError:
2022-04-24 08:29:19 +00:00
return None
2020-11-30 07:05:48 +00:00
if drawdown > self._max_allowed_drawdown:
self.log_once(
f"Trading stopped due to Max Drawdown {drawdown:.2f} > {self._max_allowed_drawdown}"
2020-12-07 10:08:54 +00:00
f" within {self.lookback_period_str}.", logger.info)
2020-11-30 07:05:48 +00:00
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(drawdown),
)
2020-11-30 07:05:48 +00:00
2022-04-24 08:29:19 +00:00
return None
2020-11-30 07:05:48 +00:00
2022-04-24 08:58:21 +00:00
def global_stop(self, date_now: datetime, side: LongShort) -> Optional[ProtectionReturn]:
2020-11-30 07:05:48 +00:00
"""
Stops trading (position entering) for all pairs
This must evaluate to true for the whole period of the "cooldown period".
:return: Tuple of [bool, until, reason].
If true, all pairs will be locked with <reason> until <until>
"""
return self._max_drawdown(date_now)
2022-04-24 08:58:21 +00:00
def stop_per_pair(
self, pair: str, date_now: datetime, side: LongShort) -> Optional[ProtectionReturn]:
2020-11-30 07:05:48 +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>
"""
2022-04-24 08:29:19 +00:00
return None