|
| 1 | +""" |
| 2 | +python -c "import examples.websocket.heartbeat" |
| 3 | +
|
| 4 | +Single example demonstrating heartbeat handling for both public and authenticated flows. |
| 5 | +
|
| 6 | +If BFX_API_KEY and BFX_API_SECRET are set in the environment, the client will |
| 7 | +authenticate and you will see heartbeats on the authenticated (chan 0) path |
| 8 | +as well. Otherwise, only public channel heartbeats are shown. |
| 9 | +""" |
| 10 | + |
| 11 | +import os |
| 12 | +from typing import Optional |
| 13 | + |
| 14 | +from bfxapi import Client |
| 15 | +from bfxapi.websocket.subscriptions import Subscription |
| 16 | + |
| 17 | + |
| 18 | +bfx = Client( |
| 19 | + api_key=os.getenv("BFX_API_KEY"), |
| 20 | + api_secret=os.getenv("BFX_API_SECRET"), |
| 21 | +) |
| 22 | + |
| 23 | + |
| 24 | +@bfx.wss.on("heartbeat") |
| 25 | +def on_heartbeat(subscription: Optional[Subscription] = None): |
| 26 | + if subscription: |
| 27 | + channel = subscription["channel"] |
| 28 | + label = subscription.get("symbol", subscription.get("key", "N/A")) |
| 29 | + print(f"Heartbeat for {channel}: {label}") |
| 30 | + else: |
| 31 | + print("Heartbeat on authenticated connection") |
| 32 | + |
| 33 | + |
| 34 | +@bfx.wss.on("authenticated") |
| 35 | +async def on_authenticated(event): |
| 36 | + print(f"Authenticated: userId={event.get('userId')}") |
| 37 | + |
| 38 | + |
| 39 | +@bfx.wss.on("open") |
| 40 | +async def on_open(): |
| 41 | + # Subscribe to a public channel to observe subscription heartbeats |
| 42 | + await bfx.wss.subscribe("ticker", symbol="tBTCUSD") |
| 43 | + |
| 44 | + |
| 45 | +print("Starting WebSocket client... Press Ctrl+C to stop.") |
| 46 | +bfx.wss.run() |
| 47 | + |
| 48 | + |
0 commit comments