WebSocket API
The GX Exchange WebSocket API provides real-time streaming of market data and account updates. It is the recommended interface for applications that need low-latency data delivery.
Connection
| Environment | URL |
|---|---|
| Mainnet | wss://api.gx.exchange/ws |
| Testnet | wss://api.gx-exchange-testnet.xyz/ws |
| Local | ws://localhost:4000 |
The WebSocket server runs on port 4000 and accepts standard WebSocket connections.
Protocol
All messages are JSON-encoded text frames. Binary frames are not supported.
Client-to-Server Messages
| Method | Description |
|---|---|
subscribe | Subscribe to a data channel |
unsubscribe | Unsubscribe from a channel |
ping | Heartbeat ping |
post | Submit exchange actions via WebSocket |
Server-to-Client Messages
All data messages include a channel field and a data field:
{
"channel": "l2Book",
"data": {
"coin": "BTC",
"levels": [...],
"time": 1700000000000
}
}Pong responses:
{ "method": "pong" }Quick Start
TypeScript
const ws = new WebSocket("wss://api.gx.exchange/ws");
ws.onopen = () => {
// Subscribe to BTC trades
ws.send(JSON.stringify({
method: "subscribe",
subscription: { type: "trades", coin: "BTC" }
}));
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg.channel === "trades") {
console.log("Trade:", msg.data);
}
};
// Keep alive
setInterval(() => ws.send(JSON.stringify({ method: "ping" })), 50000);Python
import asyncio
import json
import websockets
async def main():
async with websockets.connect("wss://api.gx.exchange/ws") as ws:
# Subscribe to BTC orderbook
await ws.send(json.dumps({
"method": "subscribe",
"subscription": {"type": "l2Book", "coin": "BTC"}
}))
async for message in ws:
msg = json.loads(message)
if msg.get("channel") == "l2Book":
levels = msg["data"]["levels"]
best_bid = levels[0][0]["px"] if levels[0] else "N/A"
best_ask = levels[1][0]["px"] if levels[1] else "N/A"
print(f"BTC bid={best_bid} ask={best_ask}")
asyncio.run(main())Sections
- Subscriptions — Available channels and subscription formats
- Post Requests — Submitting orders via WebSocket
- Timeouts and Heartbeats — Connection management