carpenstar/bybitapi-sdk-websockets
3.1.8
2024-09-01 15:38 UTC
Requires
- php: >=7.4
- carpenstar/bybitapi-sdk-core: 5.1.*
- workerman/workerman: 4.1.16
This package is auto-updated.
Last update: 2024-10-01 16:02:15 UTC
README
ByBitAPI - websockets 包
重要
这是一个与ByBit交易所交互的非官方SDK。开发完全由一个人出于热情进行,尽可能全面。所有问题,您可以通过问题、电子邮件:[mighty.vlad@gmail.com](mailto:mighty.vlad@gmail.com)或Telegram:@novisad0189联系我。
重要
此包是bybitapi-sdk-core的扩展。
要求
- PHP >= 7.4
- posix - 扩展
- pcntl - 扩展
安装
composer require carpenstar/bybitapi-sdk-websockets:3.*
应用程序实例
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 (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');
启动监听socket服务器
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();
处理来自socket服务器的回调
作为传入消息的处理程序,您需要创建自己的类,该类将扩展抽象类Carpenstar\ByBitAPI\Core\Objects\WebSockets\Channels\ChannelHandler
业务逻辑区域的入口点是handle($data, TcpConnection $connection)过程,在其中您应实现传入数据的处理。
警告
请注意,每次您订阅通道时,第一条消息都是握手消息,它将指示连接状态,而后续的消息将包含您所需的信息。
消息处理程序类示例
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 */ }
握手 - 消息
握手总是在您与socket服务器建立连接后的第一条消息,因此在进行业务逻辑之前,建议通过调用isSuccess()函数来确保连接成功,该函数将返回成功时的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" }