Fix server hang: stop CTP reconnect storm and throttle live account polling.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -2955,13 +2955,26 @@ def install_trading(app, *, login_required, require_nav, get_db, get_setting, se
|
||||
def recommend_page():
|
||||
return redirect(url_for("positions") + "#recommend")
|
||||
|
||||
def _maybe_refresh_live_account(payload: dict, mode: str) -> dict:
|
||||
"""轻量刷新权益:快照较新时跳过,避免阻塞 HTTP 线程。"""
|
||||
if not ctp_status(mode).get("connected"):
|
||||
return payload
|
||||
if payload.get("capital") and position_hub.snapshot_age_sec() < 3.0:
|
||||
return payload
|
||||
if not _live_refresh_lock.acquire(blocking=False):
|
||||
return payload
|
||||
try:
|
||||
return _apply_live_account(dict(payload), mode)
|
||||
finally:
|
||||
_live_refresh_lock.release()
|
||||
|
||||
@app.route("/api/trading/live")
|
||||
@login_required
|
||||
def api_trading_live():
|
||||
mode = get_trading_mode(get_setting)
|
||||
snap = position_hub.get_snapshot()
|
||||
if snap:
|
||||
payload = _apply_live_account(dict(snap), mode)
|
||||
payload = _maybe_refresh_live_account(dict(snap), mode)
|
||||
return jsonify(_normalize_live_payload(payload))
|
||||
payload = _refresh_trading_live_snapshot(fast=True)
|
||||
payload = _normalize_live_payload(payload)
|
||||
@@ -2993,7 +3006,7 @@ def install_trading(app, *, login_required, require_nav, get_db, get_setting, se
|
||||
mode = get_trading_mode(get_setting)
|
||||
yield sse_format(
|
||||
"positions",
|
||||
_apply_live_account(dict(snap), mode),
|
||||
_maybe_refresh_live_account(dict(snap), mode),
|
||||
)
|
||||
while True:
|
||||
try:
|
||||
|
||||
@@ -45,6 +45,12 @@ class PositionStreamHub:
|
||||
with self._lock:
|
||||
return dict(self._snapshot) if self._snapshot else None
|
||||
|
||||
def snapshot_age_sec(self) -> float:
|
||||
with self._lock:
|
||||
if not self._snapshot_ts:
|
||||
return 9999.0
|
||||
return max(0.0, time.time() - self._snapshot_ts)
|
||||
|
||||
def set_snapshot(self, data: dict) -> None:
|
||||
with self._lock:
|
||||
self._snapshot = dict(data)
|
||||
|
||||
Reference in New Issue
Block a user