Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions examples/Websocket/Public/ws-public-ticker.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
Subscribe to the public `tickers.BTCUSDT` topic with `WebsocketClient` and the
`linear` product category. No API key or secret is needed.

After installing `bybit-api`, save the displayed code as `ws-public.mjs` and run
`node ws-public.mjs`.

Register the `exception`, `response`, and `update` handlers before calling
`subscribeV5()`. The example prints the first received price and closes the
connection. It exits with a nonzero status if the subscription fails or no
price arrives within 20 seconds.

The output contains `symbol`, `lastPrice` as a decimal string, and the exchange's
`timestamp` in milliseconds. For a continuous feed, keep the connection open
and merge ticker deltas into the preceding snapshot. Bybit omits unchanged
fields from linear ticker deltas, so a message without `lastPrice` does not
mean the price is zero or unavailable. See the
[Bybit ticker stream documentation](https://bybit-exchange.github.io/docs/v5/websocket/public/ticker)
for the message contract.
46 changes: 46 additions & 0 deletions examples/Websocket/Public/ws-public-ticker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { WebsocketClient } from '../../../src/index';

const wsClient = new WebsocketClient();
const topic = 'tickers.BTCUSDT';
let stopped = false;

const timeout = setTimeout(() => {
console.error('No BTCUSDT price received within 20 seconds.');
stop(1);
}, 20_000);

function stop(exitCode = 0) {
if (stopped) return;
stopped = true;
clearTimeout(timeout);
wsClient.closeAll();
process.exitCode = exitCode;
}

wsClient.on('exception', (error) => {
console.error('WebSocket error:', error);
stop(1);
});

wsClient.on('response', (response) => {
if (response.op === 'subscribe' && response.success === false) {
console.error('Subscription rejected:', response);
stop(1);
}
});

wsClient.on('update', (message) => {
if (stopped || message.topic !== topic || !message.data?.lastPrice) return;

console.log({
symbol: message.data.symbol,
lastPrice: message.data.lastPrice,
timestamp: message.ts,
});
stop();
});

Promise.all(wsClient.subscribeV5(topic, 'linear')).catch((error) => {
console.error('Could not subscribe:', error);
stop(1);
});
Loading