carpenstar / bybitapi-sdk-websockets-v5
Requires
- php: >=7.4
- carpenstar/bybitapi-sdk-core: 5.2.*
- workerman/workerman: 4.1.16
This package is auto-updated.
Last update: 2025-05-04 00:12:17 UTC
README
Important
This is an unofficial SDK for interacting with the ByBit exchange.
Development is maintained by a single individual purely out of enthusiasm and as time permits.
Contact information:
- GitHub Issues
- Email: mighty.vlad@gmail.com
- Telegram: @novisad0189
Note
This package extends bybitapi-sdk-core
📡 Available Data Streams
Public Streams
|
|||
---|---|---|---|
Channel | Description | Official Documentation | Example |
Kline | view (EN, RU) | view | view |
OrderBook | view (EN, RU) | view | view |
Trade | view (EN, RU) | view | view |
Ticker | view (EN, RU) | view | view |
All Liquidation | view (EN, RU) | view | view |
Leverage Token - Kline | view (EN, RU) | view | view |
Leverage Token - Ticker | view (EN, RU) | view | view |
Leverage Token - Nav | view (EN, RU) | view | view |
Private Streams | |||
Channel | Description | Official Documentation | Example |
Position | In development... | view | In development... |
Execution | In development... | view | In development... |
Fast Execution | In development... | view | In development... |
Order | In development... | view | In development... |
Wallet | In development... | view | In development... |
Greek | In development... | view | In development... |
🛠Installation
composer require carpenstar/bybitapi-sdk-websockets-v5
Requirements:
- PHP ≥ 7.4
posix
extensionpcntl
extension
🚀 Using Websockets SDK in Native PHP
To subscribe to ByBit's WebSocket data stream, you need to create two files:
- Main executable file (e.g.,
socket.php
) - application entry point to run as a daemon - Message handler file (e.g.,
CallbackHandler.php
) - contains custom data processing logic
Main file (socket.php)
// socket.php use Carpenstar\ByBitAPI\BybitAPI; require_once('vendor/autoload.php'); // Include Composer autoloader // Initialize WebSocket connection // Recommended approach for public channels (no authentication) // For private channels use BybitAPI::setCredentials() to configure credentials // Note: Using ws:// instead of wss:// - Workerman will automatically establish secure connection $websocket = (new BybitAPI('ws://stream.bybit.com/v5'))->websockets();
Message handler (CallbackHandler.php)
namespace Callbacks; use Carpenstar\ByBitAPI\Core\Objects\WebSockets\Channels\ChannelHandler; // Handler class must extend ChannelHandler class CallbackHandler extends ChannelHandler { /** * Handler for successful WebSocket server connection event * * @param WebSocketConnectionResponse $message Connection data * @param TcpConnection $connection Connection object * @return void */ public function connectionHandle(WebSocketConnectionResponse $message, TcpConnection $connection): void { var_dump($message); } /** * Handler for WebSocket server exceptions * * @param ExceptionResponse $dtoMessage Exception object * @param TcpConnection $connection Connection object * @return void */ public function apiExceptionHandler(ExceptionResponse $dtoMessage, TcpConnection $connection): void { throw new ApiException($dtoMessage->getReturnMessage()); } /** * Main application business logic handler * Important: This handler persists throughout script execution * When using databases (e.g. PostgreSQL) verify connection before executing your business logic * * @param IResponseDataInterface $message Incoming message * @param TcpConnection $connection Connection object * @return void */ public function handle(IResponseDataInterface $message, TcpConnection $connection): void { var_dump($message); } }
Channel connection initialization
Select desired channel from \Carpenstar\ByBitAPI\WebSocketsV5\SocketAPI
, configure connection parameters, pass the handler instance and call execute()
to establish connection.
use Carpenstar\ByBitAPI\BybitAPI; use Callbacks\CallbackHandler; require_once('vendor/autoload.php'); // Available hosts listed in \Carpenstar\ByBitAPI\Core\Enums\WebSocketHostEnum (new BybitAPI('ws://stream.bybit.com/v5')) ->websockets() ->tickerSpot( ['BTCUSDT'], // List of trading pairs to subscribe to new CallbackHandler() // Message handler instance )->execute();
Application launch
php ./socket.php start # Debug mode php ./socket.php start -d # Daemon mode (production)
On successful connection you'll see data dump similar to documentation example.
JohnDoe@0b9374c43827:/var/www/html# php socket.php start Workerman[index.php] start in DEBUG mode -------------------------------------------- WORKERMAN -------------------------------------------- Workerman version:4.1.15 PHP version:7.4.33 Event-Loop:\Workerman\Events\Select --------------------------------------------- WORKERS --------------------------------------------- proto user worker listen processes status tcp JohnDoe none none 1 [OK] --------------------------------------------------------------------------------------------------- Press Ctrl+C to stop. Start success. object(Carpenstar\ByBitAPI\Core\Objects\WebSockets\Entity\WebSocketConnectionResponse)#13 (8) { ["success":"Carpenstar\ByBitAPI\Core\Objects\WebSockets\Entity\WebSocketConnectionResponse":private]=> bool(true) ["connectionId":"Carpenstar\ByBitAPI\Core\Objects\WebSockets\Entity\WebSocketConnectionResponse":private]=> string(36) "65daf8db-a8df-4a7a-b48f-d3b0f9228e4b" ["returnMessage":"Carpenstar\ByBitAPI\Core\Objects\WebSockets\Entity\WebSocketConnectionResponse":private]=> string(9) "subscribe" ["reqId":"Carpenstar\ByBitAPI\Core\Objects\WebSockets\Entity\WebSocketConnectionResponse":private]=> string(0) "" ["operation":"Carpenstar\ByBitAPI\Core\Objects\WebSockets\Entity\WebSocketConnectionResponse":private]=> string(9) "subscribe" ["type":"Carpenstar\ByBitAPI\Core\Objects\WebSockets\Entity\WebSocketConnectionResponse":private]=> string(0) "" ["successTopics":"Carpenstar\ByBitAPI\Core\Objects\WebSockets\Entity\WebSocketConnectionResponse":private]=> array(0) { } ["failTopics":"Carpenstar\ByBitAPI\Core\Objects\WebSockets\Entity\WebSocketConnectionResponse":private]=> array(0) { } } object(Carpenstar\ByBitAPI\WebSocketsV5\PublicStream\Ticker\Message\Spot\TickerSpotMessage)#13 (5) { ["topic"]=> string(15) "tickers.BTCUSDT" ["type"]=> string(8) "snapshot" ["timestamp"]=> object(DateTime)#15 (3) { ["date"]=> string(26) "2025-05-03 22:48:04.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" } ["sequence"]=> int(72741922262) ["data"]=> object(Carpenstar\ByBitAPI\Core\Objects\Collection\EntityCollection)#14 (1) { ["collection":protected]=> array(1) { [0]=> object(Carpenstar\ByBitAPI\WebSocketsV5\PublicStream\Ticker\Message\Spot\TickerSpotMessageItem)#17 (9) { ["symbol"]=> string(7) "BTCUSDT" ["lastPrice"]=> float(96219.9) ["highPrice24h"]=> float(96925.5) ["lowPrice24h"]=> float(95860.9) ["prevPrice24h"]=> float(96638.5) ["volume24h"]=> float(4694.676647) ["turnover24h"]=> float(452205893.24745) ["price24hPcnt"]=> float(-0.0043) ["usdIndexPrice"]=> float(96230.217967) } } } }
Technical Messages
\Carpenstar\ByBitAPI\Core\Objects\WebSockets\Entity\WebSocketConnectionResponse::class
Message received in ChannelHandler::connectionHandle()
when connection is successfully established.
Note that the set of returned fields may vary between data streams, except for $this->success
- it will always be true.
class WebSocketConnectionResponse extends AbstractResponse { // ... // Always true public function isSuccess(): bool { return $this->success; } public function getReturnMessage(): ?string { return $this->returnMessage; } public function getConnectionId(): string { return $this->connectionId; } public function getReqId(): ?string { return $this->reqId; } public function getOperation(): string { return $this->operation; } public function getType(): string { return $this->type; } public function getSuccessTopics(): array { return $this->successTopics; } public function getFailTopics(): array { return $this->failTopics; } }
\Carpenstar\ByBitAPI\Core\Objects\ExceptionResponse::class
Message received in ChannelHandler::apiExceptionHandler()
when connection to socket server fails.
class ExceptionResponse implements IResponseDataInterface { // ... // Always false public function isSuccess(): bool { return $this->isSuccess; } // May be empty public function getReturnMessage(): string { return $this->retMsg; } // Time when connection failed, depends on your server settings public function getTime(): \DateTime { return $this->time; } }
Exception Types
// This exception occurs when there's an SDK logic error Carpenstar\ByBitAPI\Core\Exceptions\SDKException::class
// This exception occurs when there's an error from ByBit's socket server Carpenstar\ByBitAPI\Core\Exceptions\ApiException::class