修复页面握库拉余额导致 database is locked 整页 500。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
dekun
2026-10-07 13:11:37 +08:00
parent c021c38e2d
commit ddacdbc1e8
2 changed files with 160 additions and 113 deletions
+116 -99
View File
@@ -275,33 +275,39 @@ def _load_state(conn):
def _sync_trading_day(conn, trading_day: str, now: Optional[datetime] = None) -> Any:
import sqlite3
row = _load_state(conn)
td = (trading_day or "").strip()
stored = str(_row_get(row, "trading_day") or "").strip()
if stored != td:
now_ms = _now_ms(now)
cooloff_active = _resolved_cooloff_until_ms(row, now_ms)
conn.execute(
"""UPDATE account_risk_state SET
trading_day=?,
manual_close_count=0,
daily_loss_count=0,
daily_frozen=0,
cooloff_until_ms=?,
cooloff_hours=?,
last_close_at_ms=?,
pending_journal_trade_id=NULL,
updated_at=?
WHERE id=1""",
(
td,
cooloff_active,
_row_get(row, "cooloff_hours") if cooloff_active else None,
_row_get(row, "last_close_at_ms") if cooloff_active else None,
(now or datetime.now()).strftime("%Y-%m-%d %H:%M:%S"),
),
)
row = _load_state(conn)
try:
conn.execute(
"""UPDATE account_risk_state SET
trading_day=?,
manual_close_count=0,
daily_loss_count=0,
daily_frozen=0,
cooloff_until_ms=?,
cooloff_hours=?,
last_close_at_ms=?,
pending_journal_trade_id=NULL,
updated_at=?
WHERE id=1""",
(
td,
cooloff_active,
_row_get(row, "cooloff_hours") if cooloff_active else None,
_row_get(row, "last_close_at_ms") if cooloff_active else None,
(now or datetime.now()).strftime("%Y-%m-%d %H:%M:%S"),
),
)
row = _load_state(conn)
except sqlite3.OperationalError:
# 页面渲染勿因跨日写库锁死而 500;下次再同步
pass
return row
@@ -800,6 +806,24 @@ def apply_position_limit_risk(
return out
def _disabled_or_fallback_risk_status(*, enabled: bool = False) -> dict[str, Any]:
return {
"enabled": bool(enabled),
"status": STATUS_NORMAL,
"status_label": STATUS_LABELS[STATUS_NORMAL],
"can_trade": True,
"reason": "",
"cooloff_until_ms": None,
"cooloff_until": None,
"manual_close_count": 0,
"daily_loss_count": 0,
"daily_frozen": False,
"daily_loss_limit": daily_loss_limit() if enabled else 0,
"pending_journal_trade_id": None,
"freeze_remaining_sec": 0,
}
def compute_account_risk_status(
conn,
*,
@@ -807,88 +831,81 @@ def compute_account_risk_status(
now: Optional[datetime] = None,
fmt_local_ms: Optional[Callable[[int], str]] = None,
) -> dict[str, Any]:
import sqlite3
if not risk_control_enabled():
return {
"enabled": False,
"status": STATUS_NORMAL,
"status_label": STATUS_LABELS[STATUS_NORMAL],
"can_trade": True,
"reason": "",
"cooloff_until_ms": None,
"cooloff_until": None,
"manual_close_count": 0,
"daily_loss_count": 0,
"daily_frozen": False,
}
row = _sync_trading_day(conn, trading_day, now=now)
now_ms = _now_ms(now)
daily_frozen = int(_row_get(row, "daily_frozen") or 0) == 1
pending = _row_get(row, "pending_journal_trade_id")
cooloff_until_ms = _resolved_cooloff_until_ms(row, now_ms)
if (
not daily_frozen
and cooloff_until_ms is not None
and _journaled_manual_cooloff_expired(
conn, trading_day=trading_day, now_ms=now_ms, pending=pending
)
):
cooloff_until_ms = None
if not daily_frozen:
_repair_stale_cooloff_row(
conn, row, now_ms=now_ms, resolved_until_ms=cooloff_until_ms, now=now
)
row = _load_state(conn)
return _disabled_or_fallback_risk_status(enabled=False)
try:
row = _sync_trading_day(conn, trading_day, now=now)
now_ms = _now_ms(now)
daily_frozen = int(_row_get(row, "daily_frozen") or 0) == 1
pending = _row_get(row, "pending_journal_trade_id")
cooloff_until_ms = _resolved_cooloff_until_ms(row, now_ms)
manual_close_count = int(_row_get(row, "manual_close_count") or 0)
daily_loss_count = int(_row_get(row, "daily_loss_count") or 0)
loss_limit = daily_loss_limit()
if (
not daily_frozen
and cooloff_until_ms is not None
and _journaled_manual_cooloff_expired(
conn, trading_day=trading_day, now_ms=now_ms, pending=pending
)
):
cooloff_until_ms = None
if not daily_frozen:
_repair_stale_cooloff_row(
conn, row, now_ms=now_ms, resolved_until_ms=cooloff_until_ms, now=now
)
row = _load_state(conn)
cooloff_until_ms = _resolved_cooloff_until_ms(row, now_ms)
manual_close_count = int(_row_get(row, "manual_close_count") or 0)
daily_loss_count = int(_row_get(row, "daily_loss_count") or 0)
loss_limit = daily_loss_limit()
status = STATUS_NORMAL
reason = ""
if daily_frozen:
status = STATUS_DAILY
parts = []
if loss_limit > 0 and daily_loss_count >= loss_limit:
parts.append(f"日亏损 {daily_loss_count}/{loss_limit} 次")
if manual_close_count >= manual_close_daily_limit():
parts.append(f"手动平仓 {manual_close_count} 次")
if not parts:
parts.append("手动平仓/日亏损达限或复盘情绪标签")
reason = "账户今日已冻结(" + "、".join(parts) + ")"
elif cooloff_until_ms is not None:
remaining_ms = cooloff_until_ms - now_ms
hours = _cooloff_hours_value(row)
status = _freeze_tier_from_remaining_ms(remaining_ms, hours)
status_label = _freeze_status_label(hours, status)
until_str = _ms_to_local_str(cooloff_until_ms, fmt_local_ms) if fmt_local_ms else None
label = status_label
reason = f"账户{label}中"
if until_str:
reason += f",至 {until_str}"
status = STATUS_NORMAL
reason = ""
if daily_frozen:
status = STATUS_DAILY
parts = []
if loss_limit > 0 and daily_loss_count >= loss_limit:
parts.append(f"日亏损 {daily_loss_count}/{loss_limit} 次")
if manual_close_count >= manual_close_daily_limit():
parts.append(f"手动平仓 {manual_close_count} 次")
if not parts:
parts.append("手动平仓/日亏损达限或复盘情绪标签")
reason = "账户今日已冻结(" + "、".join(parts) + ")"
elif cooloff_until_ms is not None:
remaining_ms = cooloff_until_ms - now_ms
hours = _cooloff_hours_value(row)
status = _freeze_tier_from_remaining_ms(remaining_ms, hours)
until_str = _ms_to_local_str(cooloff_until_ms, fmt_local_ms) if fmt_local_ms else None
reason = f"账户{_freeze_status_label(hours, status)}中"
if until_str:
reason += f",至 {until_str}"
can_trade = status == STATUS_NORMAL
freeze_remaining_sec = (
max(0, (cooloff_until_ms - now_ms) // 1000) if cooloff_until_ms is not None else 0
)
return {
"enabled": True,
"status": status,
"status_label": _freeze_status_label(_cooloff_hours_value(row), status)
if status in (STATUS_FREEZE_1H, STATUS_FREEZE_4H)
else STATUS_LABELS[status],
"can_trade": can_trade,
"reason": reason,
"cooloff_until_ms": cooloff_until_ms,
"cooloff_until": _ms_to_local_str(cooloff_until_ms, fmt_local_ms)
if fmt_local_ms and cooloff_until_ms
else None,
"manual_close_count": manual_close_count,
"daily_loss_count": daily_loss_count,
"daily_loss_limit": loss_limit,
"daily_frozen": daily_frozen,
"pending_journal_trade_id": pending,
"freeze_remaining_sec": freeze_remaining_sec if not can_trade else 0,
}
can_trade = status == STATUS_NORMAL
freeze_remaining_sec = (
max(0, (cooloff_until_ms - now_ms) // 1000) if cooloff_until_ms is not None else 0
)
return {
"enabled": True,
"status": status,
"status_label": _freeze_status_label(_cooloff_hours_value(row), status)
if status in (STATUS_FREEZE_1H, STATUS_FREEZE_4H)
else STATUS_LABELS[status],
"can_trade": can_trade,
"reason": reason,
"cooloff_until_ms": cooloff_until_ms,
"cooloff_until": _ms_to_local_str(cooloff_until_ms, fmt_local_ms)
if fmt_local_ms and cooloff_until_ms
else None,
"manual_close_count": manual_close_count,
"daily_loss_count": daily_loss_count,
"daily_loss_limit": loss_limit,
"daily_frozen": daily_frozen,
"pending_journal_trade_id": pending,
"freeze_remaining_sec": freeze_remaining_sec if not can_trade else 0,
}
except sqlite3.OperationalError:
# 渲染路径遇 database is locked 时降级为正常,避免整页 500
return _disabled_or_fallback_risk_status(enabled=True)
def account_risk_blocks_trading(