WebSocket operations provide real-time data streaming capabilities for live market data, order updates, balance changes, and position monitoring through persistent connections.
Stream live market data including tickers, order books, trades, and candlestick data.
/**
* Watch real-time ticker updates
* @param symbol - Trading pair symbol
* @param params - Additional parameters
* @returns Promise that resolves to ticker updates
*/
watchTicker(symbol: string, params?: Dict): Promise<Ticker>;
/**
* Watch real-time order book updates
* @param symbol - Trading pair symbol
* @param limit - Order book depth limit (optional)
* @param params - Additional parameters
* @returns Promise that resolves to order book updates
*/
watchOrderBook(symbol: string, limit?: number, params?: Dict): Promise<OrderBook>;
/**
* Watch real-time trade updates
* @param symbol - Trading pair symbol
* @param since - Timestamp to start from (optional)
* @param limit - Number of trades to keep (optional)
* @param params - Additional parameters
* @returns Promise that resolves to trade updates
*/
watchTrades(symbol: string, since?: number, limit?: number, params?: Dict): Promise<Trade[]>;
/**
* Watch real-time OHLCV updates
* @param symbol - Trading pair symbol
* @param timeframe - Timeframe string (e.g., '1m', '1h')
* @param since - Timestamp to start from (optional)
* @param limit - Number of candles to keep (optional)
* @param params - Additional parameters
* @returns Promise that resolves to OHLCV updates
*/
watchOHLCV(symbol: string, timeframe?: string, since?: number, limit?: number, params?: Dict): Promise<OHLCV[]>;Usage Examples:
// Watch BTC/USDT ticker
const watchTicker = async () => {
while (true) {
try {
const ticker = await exchange.watchTicker('BTC/USDT');
console.log(`BTC/USDT: $${ticker.last} (${ticker.percentage?.toFixed(2)}%)`);
} catch (error) {
console.error('Ticker error:', error.message);
break;
}
}
};
// Watch order book updates
const watchOrderBookUpdates = async () => {
while (true) {
try {
const orderBook = await exchange.watchOrderBook('BTC/USDT', 10);
const bestBid = orderBook.bids[0][0];
const bestAsk = orderBook.asks[0][0];
const spread = bestAsk - bestBid;
console.log(`Order Book - Bid: $${bestBid}, Ask: $${bestAsk}, Spread: $${spread.toFixed(2)}`);
} catch (error) {
console.error('Order book error:', error.message);
break;
}
}
};
// Watch live trades
const watchLiveTrades = async () => {
while (true) {
try {
const trades = await exchange.watchTrades('BTC/USDT');
const latestTrade = trades[trades.length - 1];
console.log(`Trade: ${latestTrade.side} ${latestTrade.amount} BTC @ $${latestTrade.price}`);
} catch (error) {
console.error('Trades error:', error.message);
break;
}
}
};
// Watch 1-minute candles
const watchCandles = async () => {
while (true) {
try {
const candles = await exchange.watchOHLCV('BTC/USDT', '1m');
const latestCandle = candles[candles.length - 1];
const [timestamp, open, high, low, close, volume] = latestCandle;
console.log(`1m Candle: O:${open} H:${high} L:${low} C:${close} V:${volume}`);
} catch (error) {
console.error('OHLCV error:', error.message);
break;
}
}
};Stream real-time account information including balance changes, order updates, and position changes.
/**
* Watch real-time balance updates
* @param params - Additional parameters
* @returns Promise that resolves to balance updates
*/
watchBalance(params?: Dict): Promise<Balances>;
/**
* Watch real-time order updates
* @param symbol - Trading pair symbol to filter by (optional)
* @param since - Timestamp to start from (optional)
* @param limit - Number of orders to keep (optional)
* @param params - Additional parameters
* @returns Promise that resolves to order updates
*/
watchOrders(symbol?: string, since?: number, limit?: number, params?: Dict): Promise<Order[]>;
/**
* Watch real-time position updates
* @param symbols - Symbols to watch (optional)
* @param since - Timestamp to start from (optional)
* @param limit - Number of positions to keep (optional)
* @param params - Additional parameters
* @returns Promise that resolves to position updates
*/
watchPositions(symbols?: string[], since?: number, limit?: number, params?: Dict): Promise<Position[]>;Usage Examples:
// Watch balance changes
const watchBalanceChanges = async () => {
while (true) {
try {
const balances = await exchange.watchBalance();
Object.entries(balances).forEach(([currency, balance]) => {
if (balance.total > 0 && currency !== 'info') {
console.log(`${currency}: ${balance.total} (${balance.free} available)`);
}
});
} catch (error) {
console.error('Balance error:', error.message);
break;
}
}
};
// Watch order updates
const watchOrderUpdates = async () => {
while (true) {
try {
const orders = await exchange.watchOrders();
orders.forEach(order => {
console.log(`Order ${order.id}: ${order.status} - ${order.filled}/${order.amount} filled`);
});
} catch (error) {
console.error('Orders error:', error.message);
break;
}
}
};
// Watch position changes (for derivatives)
const watchPositionChanges = async () => {
while (true) {
try {
const positions = await exchange.watchPositions();
positions.forEach(position => {
if (position.amount !== 0) {
console.log(`Position ${position.symbol}: ${position.side} ${position.amount}`);
if (position.unrealizedPnl !== undefined) {
console.log(` P&L: ${position.unrealizedPnl}`);
}
}
});
} catch (error) {
console.error('Positions error:', error.message);
break;
}
}
};Manage WebSocket connections and subscriptions.
/**
* Subscribe to a WebSocket channel
* @param channel - Channel name to subscribe to
* @param symbol - Symbol parameter (optional)
* @param params - Additional subscription parameters
* @returns Subscription confirmation
*/
subscribe(channel: string, symbol?: string, params?: Dict): Promise<any>;
/**
* Unsubscribe from a WebSocket channel
* @param channel - Channel name to unsubscribe from
* @param symbol - Symbol parameter (optional)
* @param params - Additional parameters
* @returns Unsubscription confirmation
*/
unsubscribe(channel: string, symbol?: string, params?: Dict): Promise<any>;
/**
* Close all WebSocket connections
*/
close(): Promise<void>;Usage Examples:
// WebSocket connection manager
class WebSocketManager {
private exchange: any;
private subscriptions = new Set<string>();
private running = false;
constructor(exchange: any) {
this.exchange = exchange;
}
async startMultipleStreams() {
this.running = true;
// Start multiple concurrent streams
const streams = [
this.watchTicker('BTC/USDT'),
this.watchTicker('ETH/USDT'),
this.watchOrderBook('BTC/USDT'),
this.watchBalance(),
this.watchOrders(),
];
// Run all streams concurrently
await Promise.all(streams);
}
private async watchTicker(symbol: string) {
console.log(`Starting ticker stream for ${symbol}`);
while (this.running) {
try {
const ticker = await this.exchange.watchTicker(symbol);
console.log(`${symbol}: $${ticker.last}`);
} catch (error) {
console.error(`Ticker ${symbol} error:`, error.message);
await this.sleep(5000); // Wait before retry
}
}
}
private async watchOrderBook(symbol: string) {
console.log(`Starting order book stream for ${symbol}`);
while (this.running) {
try {
const orderBook = await this.exchange.watchOrderBook(symbol);
const spread = orderBook.asks[0][0] - orderBook.bids[0][0];
console.log(`${symbol} spread: $${spread.toFixed(2)}`);
} catch (error) {
console.error(`Order book ${symbol} error:`, error.message);
await this.sleep(5000);
}
}
}
private async watchBalance() {
console.log('Starting balance stream');
while (this.running) {
try {
const balances = await this.exchange.watchBalance();
const nonZeroBalances = Object.entries(balances)
.filter(([currency, balance]) => balance.total > 0 && currency !== 'info')
.length;
console.log(`Active balances: ${nonZeroBalances}`);
} catch (error) {
console.error('Balance error:', error.message);
await this.sleep(5000);
}
}
}
private async watchOrders() {
console.log('Starting orders stream');
while (this.running) {
try {
const orders = await this.exchange.watchOrders();
const openOrders = orders.filter(order => order.status === 'open');
console.log(`Open orders: ${openOrders.length}`);
} catch (error) {
console.error('Orders error:', error.message);
await this.sleep(5000);
}
}
}
stop() {
console.log('Stopping all streams...');
this.running = false;
}
async close() {
this.stop();
await this.exchange.close();
console.log('All connections closed');
}
private sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
// Usage
const wsManager = new WebSocketManager(exchange);
// Start all streams
wsManager.startMultipleStreams().catch(console.error);
// Stop after 60 seconds
setTimeout(async () => {
await wsManager.close();
}, 60000);
// Handle process exit
process.on('SIGINT', async () => {
await wsManager.close();
process.exit(0);
});