feat: circuit breaker для paper trader

- ATR spike (ATR14/ATR50 > 3x) → пауза торговли
- Drawdown > 20% → пауза торговли
- Гистерезис: возобновление при ratio < 2x / DD < 10%
- Лимит позиции 30% от equity
- CB статус в portfolio summary

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-08 18:45:02 +10:00
co-authored by Claude Opus 4.6
parent 3b8c44724a
commit 21f27ff73c
+97 -9
View File
@@ -102,6 +102,13 @@ ASSET_CONFIGS = {
INITIAL_EQUITY_PER_ASSET = 10000.0
# Circuit breaker thresholds
CB_ATR_RATIO = 3.0 # ATR14 / ATR50 > 3 → pause trading
CB_ATR_RESET = 2.0 # ATR14 / ATR50 < 2 → resume trading (hysteresis)
CB_MAX_DD = 0.20 # 20% drawdown from peak → pause
CB_DD_RESET = 0.10 # drawdown recovers to 10% → resume
CB_MAX_POS_PCT = 0.30 # max 30% of equity in single position
# -- Model -------------------------------------------------------------------
@@ -171,6 +178,55 @@ def compute_atr(prices, idx, period=14):
return np.mean(trs) if trs else prices[idx] * 0.02
def check_circuit_breaker(prices, asset_state):
"""Check if circuit breaker should be active.
Returns (is_active, reason, details) tuple.
Two triggers:
1. ATR spike: ATR14 / ATR50 > CB_ATR_RATIO → volatility crisis
2. Drawdown: equity / peak_equity < (1 - CB_MAX_DD) → capital protection
Hysteresis: once active, requires lower threshold to deactivate.
"""
cb = asset_state.get("circuit_breaker", {})
was_active = cb.get("active", False)
# 1. ATR ratio check
n = len(prices)
atr14 = compute_atr(prices, n - 1, period=14)
atr50 = compute_atr(prices, n - 1, period=50)
atr_ratio = atr14 / atr50 if atr50 > 0 else 1.0
atr_trigger = atr_ratio > CB_ATR_RATIO
atr_still_high = was_active and atr_ratio > CB_ATR_RESET
# 2. Drawdown check
equity = asset_state["equity"]
peak = asset_state["peak_equity"]
dd = 1.0 - equity / peak if peak > 0 else 0.0
dd_trigger = dd > CB_MAX_DD
dd_still_bad = was_active and dd > CB_DD_RESET
# Determine state
if atr_trigger:
return True, "atr_spike", {
"atr14": round(atr14, 2), "atr50": round(atr50, 2),
"ratio": round(atr_ratio, 2),
}
if dd_trigger:
return True, "drawdown", {
"equity": round(equity, 2), "peak": round(peak, 2),
"dd_pct": round(dd * 100, 1),
}
if atr_still_high:
return True, "atr_recovering", {"ratio": round(atr_ratio, 2)}
if dd_still_bad:
return True, "dd_recovering", {"dd_pct": round(dd * 100, 1)}
return False, None, {}
def get_latest_window(prices):
"""Get the most recent window for prediction (no future prices needed)."""
if len(prices) < WINDOW_SIZE:
@@ -345,14 +401,42 @@ def daily_update():
last_price = float(prices[-1])
print(f" Last price: ${last_price:,.2f} ({last_date})")
# 0. Circuit breaker check
cb_active, cb_reason, cb_details = check_circuit_breaker(
prices, asset_state,
)
prev_cb = asset_state.get("circuit_breaker", {}).get("active", False)
asset_state["circuit_breaker"] = {
"active": cb_active,
"reason": cb_reason,
"details": cb_details,
}
if cb_active and not prev_cb:
print(f" *** CIRCUIT BREAKER ON: {cb_reason} {cb_details}")
log_event({
"type": "circuit_breaker_on",
"asset": asset,
"reason": cb_reason,
**cb_details,
})
elif not cb_active and prev_cb:
print(f" *** CIRCUIT BREAKER OFF — trading resumed")
log_event({
"type": "circuit_breaker_off",
"asset": asset,
})
elif cb_active:
print(f" *** CB ACTIVE: {cb_reason} {cb_details} — no new signals")
# 1. Check open position
pos = asset_state["open_position"]
if pos is not None:
pos = _update_position(pos, prices, dates, asset_state, asset, cfg)
asset_state["open_position"] = pos
# 2. If no open position, check for new signal
if asset_state["open_position"] is None:
# 2. If no open position AND circuit breaker is OFF, check for new signal
if asset_state["open_position"] is None and not cb_active:
_check_signal(
asset, prices, dates, cfg, asset_state, today,
)
@@ -551,13 +635,14 @@ def _check_signal(asset, prices, dates, cfg, asset_state, today):
pred_range = np.max(np.abs(pred_new[K:] - pred_new[K - 1]))
stop_dist = max(pred_range * std * 1.5, entry_price * 0.005)
# Position sizing (fixed 2% risk)
# Position sizing (fixed 2% risk, capped at CB_MAX_POS_PCT of equity)
risk_amount = equity * RISK_PER_TRADE
pos_size = risk_amount / stop_dist
pos_value = pos_size * entry_price
if pos_value > equity:
pos_size = equity / entry_price
pos_value = equity
max_pos_value = equity * CB_MAX_POS_PCT
if pos_value > max_pos_value:
pos_size = max_pos_value / entry_price
pos_value = max_pos_value
stop_price = entry_price - direction * stop_dist
@@ -618,8 +703,8 @@ def _print_portfolio_summary(state):
total_invested = 0
print(f" {'Asset':<10s} {'Equity':>10s} {'PnL':>10s} {'Trades':>7s} "
f"{'W/L':>7s} {'WR%':>5s} {'Position':>10s}")
print(f" {'─' * 62}")
f"{'W/L':>7s} {'WR%':>5s} {'Position':>10s} {'CB':>4s}")
print(f" {'─' * 68}")
for asset in ASSET_CONFIGS:
a = state["assets"].get(asset)
@@ -639,11 +724,14 @@ def _print_portfolio_summary(state):
d = "L" if pos["direction"] == 1 else "S"
pos_str = f"{d} ${pos['entry_price']:,.0f}"
cb = a.get("circuit_breaker", {})
cb_str = "ON" if cb.get("active") else "—"
total_equity += eq
total_invested += INITIAL_EQUITY_PER_ASSET
print(f" {asset:<10s} ${eq:>9,.2f} ${pnl:>+9,.2f} {trades:>7d} "
f"{wins:>3d}/{losses:<3d} {wr:>4.0f}% {pos_str:>10s}")
f"{wins:>3d}/{losses:<3d} {wr:>4.0f}% {pos_str:>10s} {cb_str:>4s}")
total_ret = (total_equity / total_invested - 1) * 100 if total_invested > 0 else 0
print(f" {'─' * 62}")