Streaming AsterDEX Data with WebSocket and Node.js
Receive real-time market data from the AsterDEX exchange through the WebSocket API and Node.js — the key to building fast and responsive trading applications.
REST vs WebSocket: Why Real-Time Matters
In our previous tutorial we used the REST API. It is a "pull" model: you send a request and receive a response. To get updates you have to poll the server continuously, which is slow and inefficient.
WebSocket is a "push" model. You establish a single persistent connection, and the server pushes data to you as soon as it becomes available. This is critical for tracking fast market movements, arbitrage and any other strategy where fractions of a second make a difference.
Prerequisites:
- Node.js and npm installed.
- A basic understanding of JavaScript and asynchrony (async/await, Promises).
Step 1: Setting Up the Project
Create a new folder for your project, initialize npm and install the `ws` library — a popular WebSocket client for Node.js.
mkdir asterdex-websocket
cd asterdex-websocket
npm init -y
npm install ws
Now create an `app.js` file — this will be our main file.
Step 2: Establishing the WebSocket Connection
We import the `ws` library and create a new client, pointing it to the AsterDEX WebSocket URL.
const WebSocket = require('ws');
// AsterDEX WebSocket endpoint
const WS_URL = 'wss://fstream.asterdex.com/ws';
console.log('Подключение к WebSocket...');
const ws = new WebSocket(WS_URL);
// Connection open handler
ws.on('open', () => {
console.log('Соединение с WebSocket успешно установлено!');
// We will subscribe to streams here
});
// Incoming message handler
ws.on('message', (data) => {
const message = JSON.parse(data);
console.log('Получено сообщение:', message);
});
// Error handler
ws.on('error', (error) => {
console.error('Ошибка WebSocket:', error);
});
// Connection close handler
ws.on('close', () => {
console.log('Соединение с WebSocket закрыто.');
});
Step 3: Subscribing to Data Streams
Once connected, the exchange will not send anything until we subscribe to the "streams" we are interested in. Subscription happens by sending a JSON message of a specific format.
Let's subscribe to the aggregated trades stream (`aggTrade`) for the `BTCUSDT` pair.
// Put this code inside the ws.on('open', ...) handler
// Subscription parameters
const subscriptionParams = {
method: "SUBSCRIBE",
params: [
"btcusdt@aggTrade" // Aggregated trades stream for BTC/USDT
],
id: 1 // Unique request ID
};
// Sending the subscription request
ws.send(JSON.stringify(subscriptionParams));
console.log('Отправлен запрос на подписку:', JSON.stringify(subscriptionParams));
If you run the code now (`node app.js`), once the connection is established you will start receiving console messages about every new trade on the BTC/USDT pair in real time.
Step 4: Subscribing to Multiple Streams and Handling Data
You can subscribe to several streams at once. Let's add the order book stream (`depth5`), which shows the five best bid and ask price levels.
// Inside ws.on('open', ...)
const multiStreamParams = {
method: "SUBSCRIBE",
params: [
"btcusdt@aggTrade", // Trades
"btcusdt@depth5@100ms" // Order book (5 levels) updated every 100 ms
],
id: 2
};
ws.send(JSON.stringify(multiStreamParams));
console.log('Отправлен запрос на подписку на несколько потоков...');
Now we need to learn how to distinguish messages from different streams. To do this, in `ws.on('message', ...)` we will inspect the object structure.
// Inside ws.on('message', ...)
const message = JSON.parse(data);
if (message.stream) {
if (message.stream.endsWith('@aggTrade')) {
const trade = message.data;
console.log(`Новая сделка по ${trade.s}: Цена=${trade.p}, Кол-во=${trade.q}`);
} else if (message.stream.endsWith('@depth5@100ms')) {
const depth = message.data;
console.log(`Обновление стакана ${message.stream.split('@')[0]}: Лучший Ask=${depth.asks[0][0]}, Лучший Bid=${depth.bids[0][0]}`);
}
} else if (message.result === null) {
console.log('Подписка успешно подтверждена!');
} else {
console.log('Системное сообщение:', message);
}
Conclusion and What's Next?
You have learned how to connect to the AsterDEX WebSocket API and receive real-time data. This is the foundation for building fast trading bots, dashboards and analytics tools.
Next steps:
- Connection resilience: Implement automatic reconnection logic for dropped connections.
- Subscription management: Add functions for dynamically subscribing and unsubscribing from streams without restarting the application.
- Authenticated endpoints: Retrieving balance or order status data over WebSocket requires authentication. Study the documentation for this.
- Integrating with your own logic: Feed the incoming data into trading logic that makes decisions and sends orders via the REST API.
For the complete list of available streams and their formats, refer to the official AsterDEX API documentation.