From 80c4ea67e7a67ea610c0a1d45c514604e3c529fa Mon Sep 17 00:00:00 2001 From: root Date: Fri, 27 Feb 2026 07:04:41 +0000 Subject: [PATCH] fix: add background snapshot loop - collect every 2s regardless of frontend --- backend/main.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/backend/main.py b/backend/main.py index 2218b5d..b758fec 100644 --- a/backend/main.py +++ b/backend/main.py @@ -73,9 +73,35 @@ def save_snapshot(rates: dict): pass # 落库失败不影响API响应 +async def background_snapshot_loop(): + """后台每2秒自动拉取费率+价格并落库,不依赖前端调用""" + while True: + try: + async with httpx.AsyncClient(timeout=5, headers=HEADERS) as client: + tasks = [client.get(f"{BINANCE_FAPI}/premiumIndex", params={"symbol": s}) for s in SYMBOLS] + responses = await asyncio.gather(*tasks, return_exceptions=True) + result = {} + for sym, resp in zip(SYMBOLS, responses): + if isinstance(resp, Exception) or resp.status_code != 200: + continue + data = resp.json() + key = sym.replace("USDT", "") + result[key] = { + "lastFundingRate": float(data["lastFundingRate"]), + "markPrice": float(data["markPrice"]), + "indexPrice": float(data["indexPrice"]), + } + if result: + save_snapshot(result) + except Exception: + pass + await asyncio.sleep(2) + + @app.on_event("startup") async def startup(): init_db() + asyncio.create_task(background_snapshot_loop()) @app.get("/api/health")