π‘ Subscribing to the Symbol Prices WebSocket
This section explains how to connect to the symbol prices WebSocket API and subscribe to receive real-time updates for specific trading pairs.
Note:
The code examples in this guide are written using Node.js with TypeScript and assume you're using thesocket.io-client
library.
β
Goal
Allow your application to receive live updates for assets such as BTCUSDT
through a reliable WebSocket connection.
π Step 1: Install the dependency
Make sure the socket.io-client
package is installed:
npm install socket.io-client
π Step 2: Establishing the WebSocket connection
import { io, Socket } from 'socket.io-client';
this.socket = io('https://symbol-prices-api.mybroker.dev/symbol-prices', {
autoConnect: true, // Automatically connects upon initialization
reconnection: true, // Enables reconnection attempts
reconnectionDelay: 5000, // Initial delay between attempts (5s)
reconnectionAttempts: 10, // Retry up to 10 times
reconnectionDelayMax: 10000, // Max delay between attempts (10s)
transports: ['websocket'], // Use only WebSocket transport
});
π Step 3: Connecting and subscribing to symbols
Once connected, we emit subscription events to start receiving price updates.
this.socket.on('connect', () => {
this.logger.log('Symbol WS connected');
this.socket.emit('last-symbol-price', 'default:BTCUSDT' });
});
Tip: Replace 'BTCUSDT' with the symbols you want to track. You can subscribe to multiple pairs inside the for loops.
β οΈ Step 4: Handling disconnections and errors
this.socket.on('disconnect', () => {
this.logger.warn('WS disconnected');
});
this.socket.on('connect_error', (err) => {
this.logger.warn('WS connect error', err);
});
this.socket.on('connect_timeout', (timeout) => {
this.logger.warn('WS timeout', timeout);
});
π₯ Step 5: Receiving price updates
Use the message event to handle incoming data from the server:
this.socket.on('message', (payload: WsMessagePayload) => {
if (payload.event !== 'symbol.price.update') return;
this.updateSymbolPrice({
price: payload.data.closePrice,
time: payload.data.time,
symbol: payload.data.pair,
slot: payload.data.slot,
});
});
The payload includes:
- pair: the asset symbol (e.g., BTCUSDT)
- closePrice: the latest closing price
- time: the timestamp of the update
- slot: the subscription slot identifier
β
Summary
Following these steps, youβll have a functional integration with the symbol prices WebSocket. Make sure to handle reconnections and validate incoming messages to keep your system robust and up-to-date.