or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

error-handling.mdexchange-management.mdindex.mdmarket-data.mdprecision.mdtrading.mdutilities.mdwebsocket.md
tile.json

websocket.mddocs/

WebSocket Streaming

WebSocket streaming provides real-time data capabilities for live market data and trading updates through persistent connections. These features are available in the pro module and enable high-frequency trading and real-time monitoring applications.

Capabilities

Real-time Market Data

Stream live market data including tickers, order books, trades, and OHLCV updates.

/**
 * Watch ticker updates for a symbol
 */
watchTicker(symbol: string, params?: object): Promise<Ticker>;

/**
 * Watch ticker updates for multiple symbols
 */
watchTickers(symbols?: string[], params?: object): Promise<Dictionary<Ticker>>;

/**
 * Watch order book updates
 */
watchOrderBook(symbol: string, limit?: number, params?: object): Promise<OrderBook>;

/**
 * Watch order book updates for multiple symbols
 */
watchOrderBooks(symbols?: string[], limit?: number, params?: object): Promise<Dictionary<OrderBook>>;

/**
 * Watch live trades
 */
watchTrades(symbol: string, since?: number, limit?: number, params?: object): Promise<Trade[]>;

/**
 * Watch trades for multiple symbols
 */
watchTradesForSymbols(symbols: string[], since?: number, limit?: number, params?: object): Promise<Dictionary<Trade[]>>;

/**
 * Watch OHLCV updates
 */
watchOHLCV(symbol: string, timeframe?: string, since?: number, limit?: number, params?: object): Promise<OHLCV[]>;

Usage Examples:

import ccxt from 'ccxt';

// Create pro exchange instance for WebSocket
const exchange = new ccxt.pro.binance({
  apiKey: 'your-api-key',
  secret: 'your-secret',
  sandbox: true,
});

// Watch ticker updates
const ticker = await exchange.watchTicker('BTC/USDT');
console.log(`${ticker.symbol}: $${ticker.last} (${ticker.percentage}%)`);

// Watch multiple tickers
while (true) {
  const tickers = await exchange.watchTickers(['BTC/USDT', 'ETH/USDT']);
  Object.values(tickers).forEach(ticker => {
    console.log(`${ticker.symbol}: $${ticker.last}`);
  });
}

// Watch order book with depth limit
while (true) {
  const orderbook = await exchange.watchOrderBook('BTC/USDT', 20);
  console.log(`Best bid: ${orderbook.bids[0][0]}, Best ask: ${orderbook.asks[0][0]}`);
  console.log(`Spread: ${orderbook.asks[0][0] - orderbook.bids[0][0]}`);
}

// Watch live trades
while (true) {
  const trades = await exchange.watchTrades('BTC/USDT');
  trades.forEach(trade => {
    console.log(`${trade.datetime}: ${trade.side} ${trade.amount} at $${trade.price}`);
  });
}

Real-time Trading Updates

Stream live updates for account balances, orders, and positions.

/**
 * Watch balance updates
 */
watchBalance(params?: object): Promise<Balances>;

/**
 * Watch order updates
 */
watchOrders(symbol?: string, since?: number, limit?: number, params?: object): Promise<Order[]>;

/**
 * Watch personal trade updates
 */
watchMyTrades(symbol?: string, since?: number, limit?: number, params?: object): Promise<Trade[]>;

/**
 * Watch position updates (for futures/margin)
 */
watchPositions(symbols?: string[], params?: object): Promise<Position[]>;

Usage Examples:

const exchange = new ccxt.pro.binance({
  apiKey: 'your-api-key',
  secret: 'your-secret',
});

// Watch balance changes
while (true) {
  const balance = await exchange.watchBalance();
  console.log('Balance update:', balance.info.eventTime);
  if (balance.BTC && balance.BTC.total > 0) {
    console.log(`BTC: ${balance.BTC.free} free, ${balance.BTC.used} used`);
  }
}

// Watch order updates
while (true) {
  const orders = await exchange.watchOrders('BTC/USDT');
  orders.forEach(order => {
    console.log(`Order ${order.id}: ${order.status} - ${order.filled}/${order.amount} filled`);
  });
}

// Watch personal trades
while (true) {
  const trades = await exchange.watchMyTrades();
  trades.forEach(trade => {
    console.log(`Trade executed: ${trade.side} ${trade.amount} ${trade.symbol} at ${trade.price}`);
    if (trade.fee) {
      console.log(`Fee: ${trade.fee.cost} ${trade.fee.currency}`);
    }
  });
}

// Watch position updates (futures)
while (true) {
  const positions = await exchange.watchPositions();
  positions.forEach(pos => {
    if (pos.size !== 0) {
      console.log(`${pos.symbol}: ${pos.side} ${pos.size} PnL: ${pos.unrealizedPnl}`);
    }
  });
}

Connection Management

Manage WebSocket connections and subscriptions.

/**
 * Close all WebSocket connections
 */
close(): Promise<void>;

/**
 * Unsubscribe from specific streams
 */
unWatchTicker(symbol: string, params?: object): Promise<void>;
unWatchTickers(symbols: string[], params?: object): Promise<void>;
unWatchOrderBook(symbol: string, params?: object): Promise<void>;
unWatchTrades(symbol: string, params?: object): Promise<void>;
unWatchOHLCV(symbol: string, timeframe?: string, params?: object): Promise<void>;
unWatchOrders(symbol?: string, params?: object): Promise<void>;
unWatchMyTrades(symbol?: string, params?: object): Promise<void>;
unWatchBalance(params?: object): Promise<void>;
unWatchPositions(symbols?: string[], params?: object): Promise<void>;

Usage Examples:

const exchange = new ccxt.pro.binance();

// Start watching data
const tickerPromise = exchange.watchTicker('BTC/USDT');
const orderbookPromise = exchange.watchOrderBook('ETH/USDT');

// Stop specific subscriptions
await exchange.unWatchTicker('BTC/USDT');
await exchange.unWatchOrderBook('ETH/USDT');

// Close all connections when done
await exchange.close();

Streaming OHLCV and Advanced Data

Stream candlestick data and advanced market information.

/**
 * Watch funding rate updates
 */
watchFundingRate(symbol: string, params?: object): Promise<FundingRate>;

/**
 * Watch liquidation updates
 */
watchLiquidations(symbol: string, since?: number, limit?: number, params?: object): Promise<Liquidation[]>;

/**
 * Watch personal liquidations
 */
watchMyLiquidations(symbol?: string, since?: number, limit?: number, params?: object): Promise<Liquidation[]>;

interface Liquidation {
  info: any;
  symbol: string;
  contracts: number;
  contractSize: number;
  price: number;
  baseValue: number;
  quoteValue: number;
  side: 'long' | 'short';
  timestamp: number;
  datetime: string;
}

Usage Examples:

const exchange = new ccxt.pro.binance();

// Watch OHLCV updates
while (true) {
  const ohlcv = await exchange.watchOHLCV('BTC/USDT', '1m');
  const latest = ohlcv[ohlcv.length - 1];
  const [timestamp, open, high, low, close, volume] = latest;
  console.log(`${new Date(timestamp)}: OHLCV ${open}/${high}/${low}/${close} Vol:${volume}`);
}

// Watch funding rate changes (futures)
while (true) {
  const fundingRate = await exchange.watchFundingRate('BTC/USDT:USDT');
  console.log(`Funding rate: ${fundingRate.fundingRate * 100}%`);
  console.log(`Next funding: ${fundingRate.nextFundingDatetime}`);
}

// Watch liquidations
while (true) {
  const liquidations = await exchange.watchLiquidations('BTC/USDT:USDT');
  liquidations.forEach(liq => {
    console.log(`Liquidation: ${liq.side} ${liq.contracts} contracts at $${liq.price}`);
  });
}

Error Handling and Reconnection

Handle WebSocket connection errors and automatic reconnection.

/**
 * Connection event handlers
 */
interface Exchange {
  onConnected?(client: any, message?: any): void;
  onError?(client: any, error: any): void;
  onClose?(client: any, error: any): void;
}

Usage Examples:

const exchange = new ccxt.pro.binance();

// Set up error handlers
exchange.onError = (client, error) => {
  console.error('WebSocket error:', error.message);
};

exchange.onClose = (client, error) => {
  console.log('WebSocket connection closed');
  if (error) {
    console.error('Close reason:', error.message);
  }
};

exchange.onConnected = (client, message) => {
  console.log('WebSocket connected successfully');
};

// Robust streaming with error handling
async function streamData() {
  try {
    while (true) {
      const ticker = await exchange.watchTicker('BTC/USDT');
      console.log(`${ticker.symbol}: $${ticker.last}`);
    }
  } catch (error) {
    console.error('Streaming error:', error.message);
    // Implement reconnection logic
    setTimeout(() => streamData(), 5000);
  }
}

streamData();

Multi-Exchange Streaming

Stream data from multiple exchanges simultaneously.

/**
 * Multiple exchange streaming pattern
 */
interface MultiExchangeStream {
  exchanges: { [name: string]: any };
  symbols: string[];
  start(): Promise<void>;
  stop(): Promise<void>;
}

Usage Examples:

// Create multiple exchange instances
const binance = new ccxt.pro.binance();
const coinbase = new ccxt.pro.coinbaseadvanced();
const kraken = new ccxt.pro.kraken();

// Stream from multiple exchanges
async function multiExchangeStream() {
  const promises = [
    binance.watchTicker('BTC/USDT'),
    coinbase.watchTicker('BTC-USD'),
    kraken.watchTicker('BTC/USD'),
  ];

  const tickers = await Promise.all(promises);
  tickers.forEach((ticker, index) => {
    const exchangeNames = ['Binance', 'Coinbase', 'Kraken'];
    console.log(`${exchangeNames[index]} ${ticker.symbol}: $${ticker.last}`);
  });
}

// Continuous multi-exchange monitoring
while (true) {
  try {
    await multiExchangeStream();
  } catch (error) {
    console.error('Multi-exchange streaming error:', error);
    await new Promise(resolve => setTimeout(resolve, 1000));
  }
}

// Cleanup
await Promise.all([
  binance.close(),
  coinbase.close(),
  kraken.close(),
]);