#!/usr/bin/env python3 """Generate the terminal's market-risk snapshot from the local Lighter lab DB. Read-only. The site ships a frozen snapshot; it is deliberately not a live feed. """ from __future__ import annotations import json import sqlite3 from collections import defaultdict from datetime import datetime, timezone from pathlib import Path DB = Path("/Users/the/development/lighter-synclab/db/lab.db") OUT = Path(__file__).resolve().parents[1] / "src/data/snapshot.json" MAX_AGE_HOURS = 6 TOP_MARKETS = 12 SYSTEM_ACCOUNTS = {"0", "281474976511093"} # Signed distance from mark, in percent. Negative = below mark, positive = above. BUCKETS = [ ("≤-10%", float("-inf"), -10.0), ("-10~-5%", -10.0, -5.0), ("-5~-3%", -5.0, -3.0), ("-3~-2%", -3.0, -2.0), ("-2~-1%", -2.0, -1.0), ("-1~0%", -1.0, 0.0), ("0~1%", 0.0, 1.0), ("1~2%", 1.0, 2.0), ("2~3%", 2.0, 3.0), ("3~5%", 3.0, 5.0), ("5~10%", 5.0, 10.0), ("≥10%", 10.0, float("inf")), ] LEVERAGE_BANDS = [ ("≤3x", 0.0, 3.0), ("3–5x", 3.0, 5.0), ("5–10x", 5.0, 10.0), ("10–20x", 10.0, 20.0), ("20–50x", 20.0, 50.0), (">50x", 50.0, float("inf")), ] def bucket_for(pct: float) -> str: for label, lo, hi in BUCKETS: if lo <= pct < hi: return label return BUCKETS[-1][0] def leverage_band_for(leverage: float) -> str: for label, lo, hi in LEVERAGE_BANDS: if lo <= leverage < hi: return label return LEVERAGE_BANDS[-1][0] def num(value) -> float: try: return float(value or 0) except (TypeError, ValueError): return 0.0 def iso(ms: int) -> str: return datetime.fromtimestamp(ms / 1000, tz=timezone.utc).isoformat().replace("+00:00", "Z") def main() -> None: con = sqlite3.connect(f"file:{DB}?mode=ro", uri=True) con.row_factory = sqlite3.Row cur = con.cursor() max_ts = cur.execute("select max(snapshot_ts) from account_positions").fetchone()[0] markets_ts = cur.execute("select max(updated_at) from market_meta").fetchone()[0] markets_ms = int(markets_ts) * 1000 if markets_ts else max_ts cutoff = max_ts - MAX_AGE_HOURS * 3600 * 1000 markets = {} for row in cur.execute( """ select market_id, symbol, mark_price, open_interest_usd, daily_quote_volume, daily_trades, default_imf, maintenance_margin_fraction from market_meta where market_type = 'perp' and status = 'active' """ ): mark = num(row["mark_price"]) if mark <= 0: continue markets[int(row["market_id"])] = { "id": int(row["market_id"]), "symbol": row["symbol"], "markPrice": mark, "oiUsd": num(row["open_interest_usd"]), "volume24h": num(row["daily_quote_volume"]), "trades24h": int(row["daily_trades"] or 0), "defaultImf": row["default_imf"], "maintenanceMarginFraction": row["maintenance_margin_fraction"], } rows = cur.execute( """ select account_index, market_id, symbol, sign, position_value, liquidation_price, initial_margin_fraction, snapshot_ts from account_positions where snapshot_ts >= ? and position_value is not null and cast(position_value as real) > 0 and liquidation_price is not null and cast(liquidation_price as real) > 0 and initial_margin_fraction is not null and cast(initial_margin_fraction as real) > 0 """, (cutoff,), ).fetchall() market_stats = defaultdict(lambda: { "positions": 0, "accounts": set(), "longNotional": 0.0, "shortNotional": 0.0, "leverageWeighted": 0.0, "maxLeverage": 0.0, "risk1": 0.0, "risk2": 0.0, "risk3": 0.0, "risk5": 0.0, "liqBuckets": {label: {"long": 0.0, "short": 0.0} for label, _, _ in BUCKETS}, "leverageBands": {label: {"long": 0.0, "short": 0.0} for label, _, _ in LEVERAGE_BANDS}, }) global_leverage = {label: {"long": 0.0, "short": 0.0} for label, _, _ in LEVERAGE_BANDS} global_buckets = {label: {"long": 0.0, "short": 0.0} for label, _, _ in BUCKETS} total_notional = 0.0 total_long = 0.0 total_short = 0.0 total_positions = 0 accounts = set() for row in rows: account = str(row["account_index"]) if account in SYSTEM_ACCOUNTS: continue market = markets.get(int(row["market_id"])) if not market: continue mark = market["markPrice"] liq = num(row["liquidation_price"]) if liq <= 0: continue notional = abs(num(row["position_value"])) if notional <= 0: continue imf = num(row["initial_margin_fraction"]) leverage = 100.0 / imf if imf > 0 else 0.0 sign = int(row["sign"] or 1) side = "long" if sign >= 0 else "short" pct = (liq - mark) / mark * 100.0 dist = abs(pct) bucket = bucket_for(pct) lev_band = leverage_band_for(leverage) total_notional += notional total_positions += 1 accounts.add(account) if side == "long": total_long += notional else: total_short += notional st = market_stats[int(row["market_id"])] st["positions"] += 1 st["accounts"].add(account) st[f"{side}Notional"] += notional st["leverageWeighted"] += notional * leverage st["maxLeverage"] = max(st["maxLeverage"], leverage) if dist <= 1: st["risk1"] += notional if dist <= 2: st["risk2"] += notional if dist <= 3: st["risk3"] += notional if dist <= 5: st["risk5"] += notional st["liqBuckets"][bucket][side] += notional st["leverageBands"][lev_band][side] += notional global_leverage[lev_band][side] += notional global_buckets[bucket][side] += notional def market_payload(market_id: int, st: dict) -> dict: m = markets[market_id] long_n = st["longNotional"] short_n = st["shortNotional"] total = long_n + short_n avg_lev = st["leverageWeighted"] / total if total else 0 liq_rows = [] for label, lo, hi in BUCKETS: cell = st["liqBuckets"][label] near = lo != float("-inf") and hi != float("inf") and abs(lo) <= 5 and abs(hi) <= 5 liq_rows.append({ "bucket": label, "fromPct": None if lo == float("-inf") else lo, "toPct": None if hi == float("inf") else hi, "near": near, "long": round(cell["long"], 2), "short": round(cell["short"], 2), "total": round(cell["long"] + cell["short"], 2), }) lev_rows = [] for label, _, _ in LEVERAGE_BANDS: cell = st["leverageBands"][label] lev_rows.append({ "band": label, "long": round(cell["long"], 2), "short": round(cell["short"], 2), "total": round(cell["long"] + cell["short"], 2), }) top_band = max(liq_rows, key=lambda x: x["total"]) near_rows = [row for row in liq_rows if row["near"]] top_near_band = max(near_rows, key=lambda x: x["total"]) if near_rows else top_band return { **m, "positions": st["positions"], "accounts": len(st["accounts"]), "notional": round(total, 2), "longNotional": round(long_n, 2), "shortNotional": round(short_n, 2), "longShare": round(long_n / total * 100, 1) if total else 0, "avgLeverage": round(avg_lev, 1), "maxLeverage": round(st["maxLeverage"], 1), "risk1": round(st["risk1"], 2), "risk2": round(st["risk2"], 2), "risk3": round(st["risk3"], 2), "risk5": round(st["risk5"], 2), "topBand": top_band, "topNearBand": top_near_band, "liqBuckets": liq_rows, "leverageBands": lev_rows, } ranked = sorted( market_stats.items(), key=lambda kv: (markets[kv[0]]["oiUsd"], kv[1]["longNotional"] + kv[1]["shortNotional"]), reverse=True, ) all_markets = [market_payload(mid, st) for mid, st in ranked] top = all_markets[:TOP_MARKETS] global_lev_rows = [] for label, _, _ in LEVERAGE_BANDS: cell = global_leverage[label] total = cell["long"] + cell["short"] global_lev_rows.append({ "band": label, "long": round(cell["long"], 2), "short": round(cell["short"], 2), "total": round(total, 2), "share": round(total / total_notional * 100, 1) if total_notional else 0, }) # Global liquidation clusters by signed price distance, with the markets # contributing the most to each cluster. cluster_markets = defaultdict(list) near_market_bands = [] for mid, st in market_stats.items(): for label, lo, hi in BUCKETS: cell = st["liqBuckets"][label] amount = cell["long"] + cell["short"] if amount > 0: cluster_markets[label].append((amount, markets[mid]["symbol"], mid)) near = lo != float("-inf") and hi != float("inf") and abs(lo) <= 5 and abs(hi) <= 5 if near: near_market_bands.append({ "amount": amount, "symbol": markets[mid]["symbol"], "marketId": mid, "bucket": label, "fromPct": lo, "toPct": hi, }) clusters = [] for label, lo, hi in BUCKETS: cell = global_buckets[label] amount = cell["long"] + cell["short"] contributors = sorted(cluster_markets[label], reverse=True)[:3] near = lo != float("-inf") and hi != float("inf") and abs(lo) <= 5 and abs(hi) <= 5 clusters.append({ "bucket": label, "fromPct": None if lo == float("-inf") else lo, "toPct": None if hi == float("inf") else hi, "near": near, "long": round(cell["long"], 2), "short": round(cell["short"], 2), "total": round(amount, 2), "share": round(amount / total_notional * 100, 1) if total_notional else 0, "topMarkets": [ {"symbol": symbol, "marketId": mid, "notional": round(v, 2)} for v, symbol, mid in contributors ], }) top_near_cluster = max(near_market_bands, key=lambda x: x["amount"], default=None) total_oi = sum(m["oiUsd"] for m in markets.values()) total_volume = sum(m["volume24h"] for m in markets.values()) total_risk1 = sum(st["risk1"] for st in market_stats.values()) total_risk3 = sum(st["risk3"] for st in market_stats.values()) total_risk5 = sum(st["risk5"] for st in market_stats.values()) weighted_leverage = sum(st["leverageWeighted"] for st in market_stats.values()) / total_notional if total_notional else 0 top_risk_market = max( (m for m in top), key=lambda m: m["risk3"], default=None, ) worst_cluster = max(clusters, key=lambda c: c["total"]) payload = { "meta": { "generatedAt": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), "dataAsOf": iso(max_ts), "marketsAsOf": iso(markets_ms), "source": "lighter-synclab / db/lab.db", "windowHours": MAX_AGE_HOURS, "accounts": len(accounts), "positions": total_positions, "marketsWithPositions": len(market_stats), "marketsTotal": len(markets), "note": f"仓位仅统计最近 {MAX_AGE_HOURS} 小时更新过的记录;标记价/OI/成交额取自生成时的 market_meta。", }, "summary": { "totalOiUsd": round(total_oi, 2), "totalVolume24h": round(total_volume, 2), "trackedNotional": round(total_notional, 2), "trackedLong": round(total_long, 2), "trackedShort": round(total_short, 2), "longShare": round(total_long / total_notional * 100, 1) if total_notional else 0, "weightedLeverage": round(weighted_leverage, 1), "risk1": round(total_risk1, 2), "risk3": round(total_risk3, 2), "risk5": round(total_risk5, 2), "risk3Share": round(total_risk3 / total_notional * 100, 1) if total_notional else 0, "nearRisk": round(total_risk5, 2), "nearRiskShare": round(total_risk5 / total_notional * 100, 1) if total_notional else 0, "topRiskMarket": top_risk_market["symbol"] if top_risk_market else None, "topNearCluster": { "symbol": top_near_cluster["symbol"], "marketId": top_near_cluster["marketId"], "bucket": top_near_cluster["bucket"], "fromPct": top_near_cluster["fromPct"], "toPct": top_near_cluster["toPct"], "notional": round(top_near_cluster["amount"], 2), } if top_near_cluster else None, "largestCluster": worst_cluster["bucket"], "largestClusterNotional": worst_cluster["total"], }, "markets": top, "allMarkets": all_markets, "leverageBands": global_lev_rows, "liqClusters": clusters, "methodology": [ "仓位来自 account_positions 的去重快照;仅保留最近 6 小时有更新的记录。", "杠杆 = 100 / initial_margin_fraction(IMF 以百分比存储)。", "清算距离 = (liquidation_price - mark_price) / mark_price;负值在现价下方,正值在上方。", "风险额 = 该价格带内仓位的 position_value 之和;不是交易所官方清算量。", "已过滤系统账户 0 与 281474976511093;未跟踪账户不在样本内。", "OI 与 24h 成交额来自 market_meta,覆盖全部 active perp 市场。", "标记价/OI 取自生成时的 market_meta;仓位快照可能更早,两个时间分别标注。", ], } OUT.parent.mkdir(parents=True, exist_ok=True) OUT.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"wrote {OUT} ({OUT.stat().st_size} bytes), markets={len(top)}, positions={total_positions}, accounts={len(accounts)}") if __name__ == "__main__": main()