""" Bybit WebSocket price bridge. Connects to Bybit's public spot stream, subscribes to configured symbols, and pushes the latest prices to GCS every few seconds. Runs continuously via launchd. """ import json import os import subprocess import sys import time from datetime import datetime, timezone try: import websocket # websocket-client except ImportError: print("ERROR: websocket-client not installed.") print("Run: pip3 install --user websocket-client") sys.exit(1) # ---------- CONFIG ---------- BUCKET = "portfolio-agent-data-388170800364" LOCAL_PATH = "/tmp/bybit_prices.json" WRITE_INTERVAL = 3 # seconds between GCS pushes SYMBOLS = [ "BTCUSDT", "ETHUSDT", ]SYMBOLS = [ "BTCUSDT", "ETHUSDT", "SOLUSDT", "ADAUSDT", "XRPUSDT", "DOGEUSDT", "AVAXUSDT", "BCHUSDT", "SHIB1000USDT", "DOTUSDT", "LINKUSDT", "MATICUSDT", ] WS_URL = "wss://stream.bybit.com/v5/public/spot" # ---------- STATE ---------- prices = {} last_write = 0 dirty = False def write_prices(force=False): """Write current price dict to local file + GCS, throttled.""" global last_write, dirty now = time.time() if not force and (now - last_write < WRITE_INTERVAL or not dirty): return if not dirty and not force: return payload = { "updated_at": int(now), "updated_iso": datetime.now(timezone.utc).isoformat(), "symbols": prices, } try: with open(LOCAL_PATH, "w") as f: json.dump(payload, f, indent=2) except Exception as e: print("local write failed: " + str(e)) return try: result = subprocess.run( ["gcloud", "storage", "cp", LOCAL_PATH, "gs://" + BUCKET + "/prices.json"], capture_output=True, timeout=10, ) if result.returncode != 0: print("GCS push rc=" + str(result.returncode) + " stderr=" + result.stderr.decode("utf-8", errors="replace")[:300]) else: last_write = now dirty = False except Exception as e: print("GCS push exception: " + str(e)) def on_message(ws, message): global dirty try: data = json.loads(message) except Exception: return topic = data.get("topic", "") if not topic.startswith("tickers."): return sym = topic.split(".", 1)[1] d = data.get("data", {}) if not sym or not d: return last = d.get("lastPrice") or d.get("markPrice") or d.get("indexPrice") if last is None: return try: last_f = float(last) except Exception: return prev = prices.get(sym, {}) if prev.get("price") != last_f: dirty = True prices[sym] = { "price": last_f, "price_24h_pct": float(d.get("price24hPcnt", 0) or 0), "high_24h": float(d.get("highPrice24h", 0) or 0), "low_24h": float(d.get("lowPrice24h", 0) or 0), "volume_24h": float(d.get("volume24h", 0) or 0), "updated_at": int(time.time()), } write_prices() def on_open(ws): print("WebSocket connected. Subscribing to " + str(len(SYMBOLS)) + " symbols...") args = ["tickers." + s for s in SYMBOLS] ws.send(json.dumps({"op": "subscribe", "args": args})) def on_error(ws, error): print("WebSocket error: " + str(error)) def on_close(ws, code, msg): print("WebSocket closed: " + str(code) + " " + str(msg)) def run(): print("Starting Bybit WebSocket bridge...") print("Symbols: " + ", ".join(SYMBOLS)) print("Writing to gs://" + BUCKET + "/prices.json every " + str(WRITE_INTERVAL) + "s") while True: try: ws = websocket.WebSocketApp( WS_URL, on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close, ) ws.run_forever(ping_interval=20, ping_timeout=10) except Exception as e: print("run_forever crashed: " + str(e)) print("Reconnecting in 5 seconds...") time.sleep(5) if __name__ == "__main__": run()