WebSocket Integration
Use the WebSocket connection for real-time market data, trade notifications, and platform events. This guide covers connection setup, subscription management, and reconnection.
Connection
Connect to wss://relay44.com/ws. The server sends periodic ping messages to keep the connection alive.
javascript
const ws = new WebSocket('wss://relay44.com/ws');
ws.onopen = () => {
console.log('Connected');
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
console.log(msg.type, msg.data);
};Subscribing to markets
After connecting, send a subscribe message to receive updates for specific markets. You can subscribe to multiple markets on the same connection.
javascript
// Subscribe to a specific market
ws.send(JSON.stringify({
channel: 'market',
market_id: '0x1234...abcd'
}));Message handling
All messages have a type field. Handle each type to update your application state.
javascript
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
switch (msg.type) {
case 'orderbook':
updateOrderBook(msg.data);
break;
case 'trade':
addTrade(msg.data);
break;
case 'position':
updatePosition(msg.data);
break;
case 'market':
updateMarketPrice(msg.data);
break;
case 'event':
handlePlatformEvent(msg.data);
break;
case 'ping':
// Keep-alive, no action needed
break;
}
};Reconnection
Implement exponential backoff for reconnection to handle network interruptions gracefully.
javascript
let retryDelay = 1000;
function connect() {
const ws = new WebSocket('wss://relay44.com/ws');
ws.onopen = () => {
retryDelay = 1000; // Reset on success
// Re-subscribe to channels
};
ws.onclose = () => {
setTimeout(connect, retryDelay);
retryDelay = Math.min(retryDelay * 2, 30000);
};
}