Skip to content

WebSocket API

Igor Sazonov edited this page Jan 31, 2026 · 3 revisions

WebSocket API

The bybit-php library includes a BybitWebSocket client for subscribing to real-time data streams from the Bybit API. This is essential for building applications that require low-latency updates.

Public Streams

Public streams provide real-time market data and do not require authentication.

use Tigusigalpa\ByBit\BybitWebSocket;

$ws = new BybitWebSocket(
    testnet: true,
    isPrivate: false
);

// Subscribe to the order book for BTC-USDT
$ws->subscribeOrderbook("BTCUSDT", 50);

// Subscribe to the ticker for BTC-USDT
$ws->subscribeTicker("BTCUSDT");

$ws->onMessage(function ($data) {
    print_r($data);
});

$ws->listen();

Private Streams

Private streams provide real-time updates on your account, orders, and positions. They require authentication with your API key and secret.

use Tigusigalpa\ByBit\BybitWebSocket;

$ws = new BybitWebSocket(
    apiKey: "your-api-key",
    apiSecret: "your-api-secret",
    testnet: true,
    isPrivate: true
);

// Subscribe to position updates
$ws->subscribePosition();

// Subscribe to order updates
$ws->subscribeOrder();

$ws->onMessage(function ($data) {
    print_r($data);
});

$ws->listen();

Available Subscription Methods

  • subscribeOrderbook(string $symbol, int $depth): Subscribe to the order book stream.
  • subscribeTrade(string $symbol): Subscribe to the public trade stream.
  • subscribeTicker(string $symbol): Subscribe to the ticker stream.
  • subscribeKline(string $symbol, string $interval): Subscribe to the k-line (candlestick) stream.
  • subscribePosition(): Subscribe to position updates (private).
  • subscribeOrder(): Subscribe to order updates (private).
  • subscribeExecution(): Subscribe to execution updates (private).
  • subscribeWallet(): Subscribe to wallet balance updates (private).

Handling WebSocket Connections

The listen() method starts the WebSocket connection and enters a loop to listen for incoming messages. You should run this in a long-running process, such as a command-line script or a daemon.

Clone this wiki locally