diff --git a/risk.py b/risk.py new file mode 100644 index 0000000..0dae55a --- /dev/null +++ b/risk.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +import datetime as dt + + +class RiskManager: + def __init__(self, daily_loss_limit: float, max_consecutive_losses: int): + self.daily_loss_limit = float(daily_loss_limit) + self.max_consecutive_losses = int(max_consecutive_losses) + self._day = dt.date.today() + self._daily_pnl = 0.0 + self._consec_losses = 0 + + def _roll_day(self) -> None: + today = dt.date.today() + if today != self._day: + self._day = today + self._daily_pnl = 0.0 + self._consec_losses = 0 + + def trading_halted(self) -> bool: + self._roll_day() + if self._daily_pnl <= -self.daily_loss_limit: + return True + if self._consec_losses >= self.max_consecutive_losses: + return True + return False + + def record_trade_result(self, pnl: float) -> None: + self._roll_day() + self._daily_pnl += float(pnl) + if pnl < 0: + self._consec_losses += 1 + else: + self._consec_losses = 0