File size: 4,165 Bytes
b0c3f0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
"""
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()