feat: DD circuit breaker с автоснятием через 48 часов
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -45,6 +45,7 @@ class CircuitBreakerConfig:
|
||||
atr_ratio_off: float = 2.0
|
||||
max_drawdown: float = 0.20
|
||||
dd_reset: float = 0.10
|
||||
dd_cooldown_hours: int = 48
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -46,13 +46,24 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
cb_active, cb_reason, cb_details = risk.check_circuit_breaker(
|
||||
prices, asset["equity"], asset["peak_equity"],
|
||||
bool(asset["cb_active"]), cfg.circuit_breaker,
|
||||
cb_reason=asset["cb_reason"],
|
||||
cb_activated_at=asset.get("cb_activated_at"),
|
||||
)
|
||||
|
||||
if cb_active != bool(asset["cb_active"]):
|
||||
action = "on" if cb_active else "off"
|
||||
log_cb_event(conn, ticker, action, cb_reason or "", str(cb_details))
|
||||
update_asset(conn, ticker, cb_active=int(cb_active), cb_reason=cb_reason)
|
||||
logs.append(f"{ticker}: CB {'ON — ' + cb_reason if cb_active else 'OFF'}")
|
||||
updates = {"cb_active": int(cb_active), "cb_reason": cb_reason}
|
||||
if cb_active:
|
||||
from datetime import datetime
|
||||
updates["cb_activated_at"] = datetime.utcnow().isoformat()
|
||||
else:
|
||||
updates["cb_activated_at"] = None
|
||||
update_asset(conn, ticker, **updates)
|
||||
reason_str = cb_reason or ""
|
||||
if cb_details.get("dd_cooldown"):
|
||||
reason_str = f"dd_cooldown ({cb_details['hours']}h)"
|
||||
logs.append(f"{ticker}: CB {'ON — ' + reason_str if cb_active else 'OFF — ' + reason_str}")
|
||||
|
||||
# 1. Check open position
|
||||
pos = get_open_position(conn, ticker)
|
||||
|
||||
@@ -67,7 +67,9 @@ def is_stopped(price: float, stop_price: float, direction: int) -> bool:
|
||||
|
||||
|
||||
def check_circuit_breaker(prices: np.ndarray, equity: float, peak_equity: float,
|
||||
was_active: bool, cb_cfg: CircuitBreakerConfig
|
||||
was_active: bool, cb_cfg: CircuitBreakerConfig,
|
||||
cb_reason: str | None = None,
|
||||
cb_activated_at: str | None = None,
|
||||
) -> tuple[bool, str | None, dict]:
|
||||
"""Check if circuit breaker should be active.
|
||||
|
||||
@@ -96,7 +98,18 @@ def check_circuit_breaker(prices: np.ndarray, equity: float, peak_equity: float,
|
||||
if was_active:
|
||||
if atr_ratio > cb_cfg.atr_ratio_off:
|
||||
return True, "atr_recovering", {"ratio": round(atr_ratio, 2)}
|
||||
if dd > cb_cfg.dd_reset:
|
||||
|
||||
# DD cooldown: auto-release after N hours
|
||||
if cb_reason and cb_reason.startswith("d") and cb_activated_at:
|
||||
from datetime import datetime
|
||||
try:
|
||||
activated = datetime.fromisoformat(cb_activated_at)
|
||||
hours_elapsed = (datetime.utcnow() - activated).total_seconds() / 3600
|
||||
if hours_elapsed >= cb_cfg.dd_cooldown_hours:
|
||||
return False, None, {"dd_cooldown": True,
|
||||
"hours": round(hours_elapsed, 1)}
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
return True, "dd_recovering", {"dd_pct": round(dd * 100, 1)}
|
||||
|
||||
return False, None, {}
|
||||
|
||||
@@ -35,6 +35,7 @@ def init_db(conn: sqlite3.Connection) -> None:
|
||||
last_train_date TEXT,
|
||||
cb_active INTEGER DEFAULT 0,
|
||||
cb_reason TEXT,
|
||||
cb_activated_at TEXT,
|
||||
created_at TEXT DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
@@ -95,6 +96,10 @@ def init_db(conn: sqlite3.Connection) -> None:
|
||||
CREATE INDEX IF NOT EXISTS idx_signals_ticker ON signals(ticker);
|
||||
CREATE INDEX IF NOT EXISTS idx_equity_ticker ON equity_snapshots(ticker);
|
||||
""")
|
||||
# Migration: add cb_activated_at if missing
|
||||
cols = {r[1] for r in conn.execute("PRAGMA table_info(assets)").fetchall()}
|
||||
if "cb_activated_at" not in cols:
|
||||
conn.execute("ALTER TABLE assets ADD COLUMN cb_activated_at TEXT")
|
||||
conn.commit()
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user