7.1 KiB
Websocket API
Class: WebsocketClient
The WebsocketClient inherits from EventEmitter. After establishing a
connection, the client sends heartbeats in regular intervalls, and reconnects
to the server once connection has been lost.
new WebsocketClient([options][, logger])
options{Object} Configuration optionskey{String} Bybit API Key. Only needed if private topics are subscribedsecret{String} Bybit private Key. Only needed if private topics are subscribedlivenet{Bool} Weather to connect to livenet (true). Defaultfalse.pingInterval{Integer} Interval in ms for heartbeat ping. Default:10000,pongTimeout{Integer} Timeout in ms waiting for heartbeat pong response from server. Default:1000,reconnectTimeout{Integer} Timeout in ms the client waits before trying to reconnect after a lost connection. Default: 500
logger{Object} Optional custom logger
Custom logger must contain the following methods:
const logger = {
silly: function(message, data) {},
debug: function(message, data) {},
notice: function(message, data) {},
info: function(message, data) {},
warning: function(message, data) {},
error: function(message, data) {},
}
ws.subscribe(topics)
topics{String|Array} Single topic as string or multiple topics as array of strings. Subscribe to one or multiple topics. See available topics
ws.unsubscribe(topics)
topics{String|Array} Single topic as string or multiple topics as array of strings. Unsubscribe from one or multiple topics.
ws.close()
Close the connection to the server.
Event: 'open'
Emmited when the connection has been opened for the first time.
Event: 'reconnected'
Emmited when the client has been opened after a reconnect.
Event: 'update'
message{Object}
Emmited whenever an update to a subscribed topic occurs.
Event: 'response'
response{Object}success{Bool}ret_msg{String} empty if operation was successfull, otherwise error message.conn_id{String} connection idrequest{Object} Original request, to which the response belongsop{String} operationargs{Array} Request Arguments
Emited when the server responds to an operation sent by the client (usually after subscribing to a topic).
Event: 'close'
Emitted when the connection has been finally closed, after a call to ws.close()
Event: 'reconnect'
Emitted when the connection has been closed, but the client will try to reconnect.
Event: 'error'
error{Error}
Emitted when an error occurs.
Available Topics
Generaly all public and private topics are available.
Private topics
Positions of your account
All positions of your account.
Topic: position
Execution message
Execution message, whenever an order has been (partially) filled.
Topic: execution
Update for your orders
Updates for your active orders
Topic: order
Update for your conditional orders
Updates for your active conditional orders
Topic: stop_order
Public topics
Candlestick chart
Candlestick OHLC "candles" for selected symbol and interval.
Example topic: klineV2.BTCUSD.1m
Real-time trading information
All trades as they occur.
Topic: trade
Daily insurance fund update
Topic: insurance
OrderBook of 25 depth per side
OrderBook for selected symbol
Example topic: orderBookL2_25.BTCUSD
OrderBook of 200 depth per side
OrderBook for selected symbol
Example topic: orderBook_200.100ms.BTCUS
Latest information for symbol
Latest information for selected symbol
Example topic: instrument_info.100ms.BTCUSD
Examples
Klines
const {WebsocketClient} = require('bybit-api');
const API_KEY = 'xxx';
const PRIVATE_KEY = 'yyy';
const ws = new WebsocketClient({key: API_KEY, secret: PRIVATE_KEY});
ws.subscribe(['position', 'execution', 'trade']);
ws.subscribe('kline.BTCUSD.1m');
ws.on('open', function() {
console.log('connection open');
});
ws.on('update', function(message) {
console.log('update', message);
});
ws.on('response', function(response) {
console.log('response', response);
});
ws.on('close', function() {
console.log('connection closed');
});
ws.on('error', function(err) {
console.error('ERR', err);
});
OrderBook Events
const { WebsocketClient, DefaultLogger } = require('bybit-api');
const { OrderBooksStore, OrderBookLevel } = require('orderbooks');
const OrderBooks = new OrderBooksStore({ traceLog: true, checkTimestamps: false });
// connect to a websocket and relay orderbook events to handlers
DefaultLogger.silly = () => {};
const ws = new WebsocketClient({ livenet: true });
ws.on('update', message => {
if (message.topic.toLowerCase().startsWith('orderbook')) {
return handleOrderbookUpdate(message);
}
});
ws.subscribe('orderBookL2_25.BTCUSD');
// parse orderbook messages, detect snapshot vs delta, and format properties using OrderBookLevel
const handleOrderbookUpdate = message => {
const { topic, type, data, timestamp_e6 } = message;
const [ topicKey, symbol ] = topic.split('.');
if (type == 'snapshot') {
return OrderBooks.handleSnapshot(symbol, data.map(mapBybitBookSlice), timestamp_e6 / 1000, message).print();
}
if (type == 'delta') {
const deleteLevels = data.delete.map(mapBybitBookSlice);
const updateLevels = data.update.map(mapBybitBookSlice);
const insertLevels = data.insert.map(mapBybitBookSlice);
return OrderBooks.handleDelta(
symbol,
deleteLevels,
updateLevels,
insertLevels,
timestamp_e6 / 1000
).print();
}
}
// Low level map of exchange properties to expected local properties
const mapBybitBookSlice = level => {
return OrderBookLevel(level.symbol, +level.price, level.side, level.size);
};