Spot WebSocket Guide
REST APIs are great for executing actions (like placing orders), but they are too slow for monitoring the market. For real-time data, you should use the WebSocket API.
This guide covers connecting, authenticating, and handling real-time streams.
Prerequisites
- Endpoint:
wss://api.big.one/ws/v2 - Library: We recommend
websockets(Python) orws(Node.js). - Protocol: JSON is the default and easiest to use.
Lesson 1: Connection & Heartbeat
BigONE's WebSocket server requires you to keep the connection alive. If you are silent for too long, the server will disconnect you.
The Logic
- Connect to
wss://api.big.one/ws/v2. - Every 30 seconds, send a Ping frame or a dummy message.
- Listen for
PINGmessages from the server and reply withPONG(most libraries handle this automatically).
import asyncio
import websockets
import json
URL = "wss://api.big.one/ws/v2"
async def connect():
async with websockets.connect(URL) as websocket:
print("Connected!")
# Keep-Alive Loop (Simplified)
while True:
try:
msg = await websocket.recv()
print(f"< {msg}")
except websockets.exceptions.ConnectionClosed:
print("Disconnected")
break
Lesson 2: Subscribing to Public Channels
You don't need authentication to watch public market data like the Order Book or Recent Trades.
The Request Format
Every request needs a unique requestId.
{
"requestId": "1",
"subscribeMarketDepthRequest": {
"market": "BTC-USDT"
}
}
Handling Order Book Data
The Order Book stream sends two types of messages:
- Snapshot: The full order book (Bids + Asks). Sent immediately after subscription.
- Update: Incremental changes.
For simple bots, you can just use the Snapshot and re-subscribe periodically. For high-frequency trading, you must apply the Updates to your local snapshot.
Lesson 3: Authentication (Private Channels)
To receive updates about Your Orders or Your Balances, you must log in.
The Logic
- Connect.
- Immediately send the
authenticateCustomerRequestwith your JWT. - Wait for the success response.
- Then subscribe to private channels.
Payload:
{
"requestId": "auth-1",
"authenticateCustomerRequest": {
"token": "Bearer YOUR_JWT_TOKEN"
}
}
Complete Example
This script connects, authenticates, and watches both the BTC-USDT Order Book and Your Order Status.
import asyncio
import websockets
import json
import time
import jwt # pip install PyJWT
# --- Config ---
API_KEY = "YOUR_KEY"
SECRET_KEY = "YOUR_SECRET"
WS_URL = "wss://api.big.one/ws/v2"
def generate_token():
payload = {
"sub": API_KEY,
"nonce": int(time.time() * 1000000),
"iat": int(time.time()),
"exp": int(time.time()) + 60 # Token for handshake only
}
return jwt.encode(payload, SECRET_KEY, algorithm="HS256")
async def run():
async with websockets.connect(WS_URL) as ws:
print("1. Connected")
# 2. Authenticate
token = generate_token()
auth_req = {
"requestId": "auth",
"authenticateCustomerRequest": {"token": f"Bearer {token}"}
}
await ws.send(json.dumps(auth_req))
print("2. Sent Auth...")
# 3. Subscribe
subs = [
# Public: Order Book
{
"requestId": "sub-depth",
"subscribeMarketDepthRequest": {"market": "BTC-USDT"}
},
# Private: My Orders
{
"requestId": "sub-orders",
"subscribeViewerOrdersRequest": {"market": "BTC-USDT"}
}
]
for sub in subs:
await ws.send(json.dumps(sub))
print("3. Subscribed")
# 4. Loop & Listen
while True:
response = await ws.recv()
data = json.loads(response)
# Check for Errors
if "error" in data:
print(f"ERROR: {data['error']}")
continue
# Identify Message Type
if "marketDepth" in data:
bids = data['marketDepth'].get('bids', [])
best_bid = bids[0] if bids else "None"
print(f"[Depth] Best Bid: {best_bid}")
elif "orderUpdate" in data:
order = data['orderUpdate']
print(f"[Order] {order['id']} is {order['state']}")
if __name__ == "__main__":
asyncio.run(run())
Conclusion
WebSockets are essential for responding to market moves.
Key Takeaways:
- Heartbeat: Ensure your library handles Pings or implement a manual Keep-Alive.
- Sequence: Always Authenticate before subscribing to private channels.
- Data Flow: Handle initial Snapshots differently from subsequent Updates.
Next Steps:
- Read the Spot WebSocket Reference for the full list of channels.
- Implement a local Order Book cache that applies
marketDepthupdates efficiently.