fix: add background snapshot loop - collect every 2s regardless of frontend
This commit is contained in:
parent
4f0cc7c393
commit
80c4ea67e7
@ -73,9 +73,35 @@ def save_snapshot(rates: dict):
|
|||||||
pass # 落库失败不影响API响应
|
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")
|
@app.on_event("startup")
|
||||||
async def startup():
|
async def startup():
|
||||||
init_db()
|
init_db()
|
||||||
|
asyncio.create_task(background_snapshot_loop())
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/health")
|
@app.get("/api/health")
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user