PHP code example of carpenstar / bybitapi-sdk-websockets

1. Go to this page and download the library: Download carpenstar/bybitapi-sdk-websockets library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

carpenstar / bybitapi-sdk-websockets example snippets


use Carpenstar\ByBitAPI\BybitAPI;

// Creating a client instance
$apiClient = new BybitAPI();


use Carpenstar\ByBitAPI\BybitAPI;
use Carpenstar\ByBitAPI\WebSockets\Enums\WebSocketHostEnum;

$apiClient = new BybitApi();

// General form for setting connection parameters

/**
 * @param $host - host of the socket server to connect to. For possible values, see Carpenstar\ByBitAPI\WebSockets\Enums\WebSocketHostEnum 
 * @param $apiKey - API key (BitAPI\WebSockets\Enums\WebSocketHostEnum 
 * Information about current hosts is contained in the official documentation:
 * - Derivatives: https://bybit-exchange.github.io/docs/derivatives/ws/connect
 * - Spot: https://bybit-exchange.github.io/docs/spot/ws/connect
 */
$apiClient->setHost(WebSocketHostEnum::WEBSOCKET_HOST_DEV);

/**
 * @param $apiKey - API key (

use Carpenstar\ByBitAPI\BybitAPI;
use Carpenstar\ByBitAPI\WebSockets\Enums\WebSocketHostEnum;
use Carpenstar\ByBitAPI\WebSockets\Spot\PublicChannels\Tickers\TickersChannel;
use Carpenstar\ByBitAPI\WebSockets\Spot\PublicChannels\Tickers\Argument\TickersArgument;

use MyCustom\Workspace\CallbackHadler;

$apiClient = new BybitApi();

// Setting connection parameters
$apiClient->setCredentials(WebSocketHostEnum::WEBSOCKET_HOST_DEV);

// preparing connection to websocket server
/**
 * The values ​​of the $channel and $option parameters can be found in the documentation
 * on the page of each channel in this repository
 * 
 * @param $channel - name of the class that handles the connection to the channel (see in the "Class websocket-channel" block)
 * @param $option - channel subscription options object (see "CHANNEL SUBSCRIPTION OPTIONS" section)
 * @param $callback - object of custom handler of messages from socket server
 */
$apiClient->websocket(TickersChannel::class, new TickersArgument("BTCUSDT"), new CallbackHadler());

// Starting the message listening process
$apiClient->execute();



namespace MyCustom\Workspace;

use Workerman\Connection\TcpConnection;
use Carpenstar\ByBitAPI\Core\Objects\Entity\WebSocketConnectionResponse;

class CallbackHadler extends ChannelHandler
{
    /**
     * @param $data - DTO collected based on data received from the socket server.
     * Each channel's $data property accepts different objects, so information about the received DTO
     * should be found on the channel documentation page.
     * 
     * In the example below we will use the DTO received when listening to the channel
     * Carpenstar\ByBitAPI\WebSockets\Spot\PublicChannels\Tickers\TickersChannel
     * 
     * @param TcpConnection $connection - socket connection object
     */ 
    public function handle($data, TcpConnection $connection): void
    {
        // The first message is always a WebSocketConnectionResponse object, from which you can get information about the current connection.
        if (is_a($data, WebSocketConnectionResponse::class) && !$data->isSuccess()) {
            $connection->close();
            throw new \Exception('Failed connection attempt. Error: ' . $data->getReturnMessage());
        } elseif (is_a($data, WebSocketConnectionResponse::class)) {
            echo "// Initial Connection Data: \n";
            echo "Success Connection: {$data->isSuccess()} \n";
            echo "Operation: {$data->getOperation()} \n";
            echo "Return Message: {$data->getReturnMessage()} \n";
            echo "Connection ID: {$data->getConnectionId()} \n";
            echo "Req ID: {$data->getReqId()} \n";
            return;
        }

        /**
         * @param \Carpenstar\ByBitAPI\WebSockets\Spot\PublicChannels\Tickers\Entities\TickersResponse $data
         */
        echo "\n ----- \n";
        echo "\nINCOMING MESSAGE: \n";
        echo "Topic: {$data->getTopic()} \n";
        echo "Type: {$data->getType()} \n";
        echo "Generate Time: {$data->getTimestamp()->format('Y-m-d H:i:s')} \n";
        
        /**
         * @param \Carpenstar\ByBitAPI\WebSockets\Spot\PublicChannels\Tickers\Entities\TickersResponseItem $tickerItem
         */
        foreach($data->getData() as $tickerItem) {
            echo "Ticker Time: {$tickerItem->getTimestamp()->format('Y-m-d H:i:s')} \n";
            echo "Symbol: {$tickerItem->getSymbol()} \n";
            echo "Open Price: {$tickerItem->getOpenPrice()} \n";
            echo "Clode Price: {$tickerItem->getClosePrice()} \n";
            echo "High Price: {$tickerItem->getHighPrice()} \n";
            echo "Low Price: {$tickerItem->getLowPrice()} \n";
            echo "Trading Volume {$tickerItem->getTradingVolume()} \n";
            echo "Trading Quote Volume: {$tickerItem->getTradingQuoteVolume()} \n";
            echo "Change: {$tickerItem->getChange()} \n";
            echo "USD Index Price: {$tickerItem->getUsdIndexPrice()} \n";
        }
    }

         /**
         * Result of launching the channel listener.
         * The initiating and first two incoming messages are displayed
         * 
         * // Initial Connection Data: 
         * Success Connection: 1 
         * Operation: subscribe 
         * Return Message:  
         * Connection ID: 24fe3f11-bfa5-4fda-acd9-ffd616ad3c48 
         * Req ID:  
         * 
         *  ----- 
         * 
         * INCOMING MESSAGE: 
         * Topic: tickers.BTCUSDT 
         * Type: snapshot 
         * Generate Time: 2024-08-29 19:18:49 
         * Ticker Time: 2024-08-29 19:18:49 
         * Symbol: BTCUSDT 
         * Open Price: 59380.4 
         * Clode Price: 59246.47 
         * High Price: 61175.07 
         * Low Price: 58625.23 
         * Trading Volume 19635.864663 
         * Trading Quote Volume: 1171866931.0697 
         * Change: -0.0023 
         * USD Index Price: 59261.344699 
         * 
        * ----- 
         * 
         * INCOMING MESSAGE: 
         * Topic: tickers.BTCUSDT 
         * Type: snapshot 
         * Generate Time: 2024-08-29 19:18:49 
         * Ticker Time: 2024-08-29 19:18:49 
         * Symbol: BTCUSDT 
         * Open Price: 59380.4 
         * Clode Price: 59247.65 
         * High Price: 61175.07 
         * Low Price: 58625.23 
         * Trading Volume 19635.865702 
         * Trading Quote Volume: 1171866992.6277 
         * Change: -0.0022 
         * USD Index Price: 59261.344699 
         */
}



namespace Carpenstar\ByBitAPI\Core\Objects\Entity;

use Carpenstar\ByBitAPI\Core\Objects\AbstractResponse;

class WebSocketConnectionResponse extends AbstractResponse
{
    private bool $success;
    private ?string $returnMessage;
    private string $connectionId;
    private ?string $reqId;
    private string $operation;

    public function __construct(array $data)
    {
        $this->success = $data['success'];
        $this->returnMessage = $data['retm_msg'] ?? null;
        $this->connectionId = $data['conn_id'];
        $this->reqId = $data['req_id'] ?? null;
        $this->operation = $data['op'];
    }

    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;
    }
}

// Structure dump:

object(Carpenstar\ByBitAPI\Core\Objects\Entity\WebSocketConnectionResponse)#15 (5) {
  ["success":"Carpenstar\ByBitAPI\Core\Objects\Entity\WebSocketConnectionResponse":private]=>
  bool(true)
  ["returnMessage":"Carpenstar\ByBitAPI\Core\Objects\Entity\WebSocketConnectionResponse":private]=>
  NULL
  ["connectionId":"Carpenstar\ByBitAPI\Core\Objects\Entity\WebSocketConnectionResponse":private]=>
  string(36) "493df477-29fe-4c6a-ac16-d240f6cd3708"
  ["reqId":"Carpenstar\ByBitAPI\Core\Objects\Entity\WebSocketConnectionResponse":private]=>
  string(0) ""
  ["operation":"Carpenstar\ByBitAPI\Core\Objects\Entity\WebSocketConnectionResponse":private]=>
  string(9) "subscribe"
}