carpenstar/bybitapi-sdk-websockets
最新稳定版本:3.1.8
Composer 安装命令:
composer require carpenstar/bybitapi-sdk-websockets
包简介
README 文档
README
Caution
The Bybit exchange has deprecated its v3 API functionality - this package is now obsolete and has been archived For v5 API support, please use the bybitapi-sdk-websockets-v5 package instead
ByBitAPI - websockets package
Important
This is an unofficial SDK for interaction with the ByBit exchange. The development is carried out by one person solely on enthusiasm and as far as possible For all questions, you can contact me in Issues, by email: mighty.vlad@gmail.com or in telegram: @novisad0189
Important
This package is an extension of bybitapi-sdk-core
Requirements
- PHP >= 7.4
- posix - extension
- pcntl - extension
Install
composer require carpenstar/bybitapi-sdk-websockets:3.*
| AVAILABLE CHANNELS | ||||
|---|---|---|---|---|
| SPOT | ||||
| Channel name | Access | View | Offical documentation | Language |
| Book Ticker | publicEndpoint | view | view | EN, RU |
| Kline | publicEndpoint | view | view | EN, RU |
| Order Book | publicEndpoint | view | view | EN, RU |
| Public Trade | publicEndpoint | view | view | EN, RU |
| Tickers | publicEndpoint | view | view | EN, RU |
| DERIVATIVES | ||||
| Channel name | Access | View | Offical documentation | Language |
| Kline | publicEndpoint | view | view | EN, RU |
| Liquidation | publicEndpoint | view | view | EN, RU |
| Order Book | publicEndpoint | view | view | EN, RU |
| Public Trade | publicEndpoint | view | view | EN, RU |
| Tickers | publicEndpoint | view | view | EN, RU |
Application instance
use Carpenstar\ByBitAPI\BybitAPI; // Creating a client instance $apiClient = new BybitAPI();
Setting connection parameters
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 (required when connecting to private channels) * @param $apiSecret - secret key (required when connecting to private channels) */ $apiClient->setCredentials(WebSocketHostEnum::WEBSOCKET_HOST_DEV, '098f6bcd4621d3', '73cade4e832627b4f6'); // Separate form for setting connection parameters; /** * @param $host - host of the socket server to connect to. For possible values, see Carpenstar\ByBitAPI\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 (required when connecting to private channels) */ $apiClient->setApiKey('098f6bcd4621d3'); /** * @param $apiSecret - secret key (required when connecting to private channels) */ $apiClient->setSecret('73cade4e832627b4f6');
Starting socket server listening
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();
Processing callbacks from a socket server
As a handler for incoming messages, you need to create your own class that will extend the abstract class Carpenstar\ByBitAPI\Core\Objects\WebSockets\Channels\ChannelHandler
The entry point to the business logic zone is the procedure handle($data, TcpConnection $connection) inside which you should implement the processing of incoming data.
Warning
Please note that each time you subscribe to a channel, the first message that comes is a handshake message, which will indicate the connection status, and only the following messages will contain the information you need.
Example of a message handler class:
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 */ }
Handshake - message
Handshake always comes as the first message after you have established a connection to the socket server, so before starting the business logic, it is recommended to make sure that the connection was successful by calling the isSuccess() function, which will return if successful true
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" }
carpenstar/bybitapi-sdk-websockets 适用场景与选型建议
carpenstar/bybitapi-sdk-websockets 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 100 次下载、GitHub Stars 达 1, 最近一次更新时间为 2023 年 05 月 07 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 carpenstar/bybitapi-sdk-websockets 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 carpenstar/bybitapi-sdk-websockets 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 100
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 21
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2023-05-07