kucoin/kucoin-universal-sdk
Composer 安装命令:
composer require kucoin/kucoin-universal-sdk
包简介
Official KuCoin Universal SDK
README 文档
README
Welcome to the PHP implementation of the KuCoin Universal SDK. This SDK is built based on KuCoin API specifications to provide a comprehensive and optimized interface for interacting with the KuCoin platform.
Note
This PHP SDK is maintained in two repositories:
kucoin/kucoin-universal-sdk: the main monorepo with SDKs for multiple languages. The PHP code resides in/sdk/php.kucoin/kucoin-universal-php-sdk: a standalone mirror for Composer/Packagist publishing. It is synced from the main repo using Git Subtree.
For an overview of the project and SDKs in other languages, refer to the Main README.
📦 Installation
Latest Version: 0.1.3-alpha
Note: This SDK is currently in the Alpha phase. We are actively iterating and improving its features, stability, and documentation. Feedback and contributions are highly encouraged to help us refine the SDK.
Install the SDK using composer:
composer require kucoin/kucoin-universal-sdk=0.1.3-alpha
📖 Getting Started
Here's a quick example to get you started with the SDK in PHP.
<?php use KuCoin\UniversalSDK\Api\DefaultClient; use KuCoin\UniversalSDK\Common\Logger; use KuCoin\UniversalSDK\Generate\Spot\Market\GetPartOrderBookReq; use KuCoin\UniversalSDK\Model\ClientOptionBuilder; use KuCoin\UniversalSDK\Model\Constants; use KuCoin\UniversalSDK\Model\TransportOptionBuilder; include '../vendor/autoload.php'; function stringifyDepth($depth): string { return implode(', ', array_map(function ($row) { return '[' . implode(', ', $row) . ']'; }, $depth)); } function example() { // Retrieve API secret information from environment variables $key = getenv('API_KEY') ?: ''; $secret = getenv('API_SECRET') ?: ''; $passphrase = getenv('API_PASSPHRASE') ?: ''; // Set specific options, others will fall back to default values $httpTransportOption = (new TransportOptionBuilder()) ->setKeepAlive(true) ->setMaxConnections(10) ->build(); // Create a client using the specified options $clientOption = (new ClientOptionBuilder()) ->setKey($key) ->setSecret($secret) ->setPassphrase($passphrase) ->setSpotEndpoint(Constants::GLOBAL_API_ENDPOINT) ->setFuturesEndpoint(Constants::GLOBAL_FUTURES_API_ENDPOINT) ->setBrokerEndpoint(Constants::GLOBAL_BROKER_API_ENDPOINT) ->setTransportOption($httpTransportOption) ->build(); $client = new DefaultClient($clientOption); // Get the Restful Service $kucoinRestService = $client->restService(); $spotMarketApi = $kucoinRestService->getSpotService()->getMarketApi(); // Query partial order book depth data (aggregated by price). // Build the request using the builder pattern. $request = GetPartOrderBookReq::builder() ->setSymbol("BTC-USDT") ->setSize("20") ->build(); // Or build the request using an array. // Ensure that the keys in the array match the field names in the API documentation, // not the variable names in the class. This is useful when migrating code from an older SDK. $request = GetPartOrderBookReq::create(["symbol" => "BTC-USDT", "size" => "20"]); $response = $spotMarketApi->getPartOrderBook($request); Logger::info(sprintf( "time=%d, sequence=%d, bids=%s, asks=%s", $response->time, $response->sequence, stringifyDepth($response->bids), stringifyDepth($response->asks) )); } if (php_sapi_name() === 'cli') { example(); }
📚 Documentation
Official Documentation: KuCoin API Docs
📂 Examples
Explore more examples in the example/ directory for advanced usage.
📋 Changelog
For a detailed list of changes, see the Changelog.
📌 Special Notes on APIs
This section provides specific considerations and recommendations for using the REST and WebSocket APIs.
REST API Notes
Client Features
-
Advanced HTTP Handling:
- Supports retries, keep-alive connections, and configurable concurrency limits for robust request execution.
- Supports both Guzzle and Saber (Swoole) as underlying HTTP clients.
- Use
useCoroutineHttp=trueto enable high-performance coroutine HTTP requests (requiresext-swooleandswlib/saber).
-
Rich Response Details:
- Includes rate-limiting information and raw response data in API responses for better debugging and control.
-
Public API Access:
- For public endpoints, API keys are not required, simplifying integration for non-authenticated use cases.
WebSocket API Notes
Client Features
- Flexible Service Creation:
- Supports creating services for public/private channels in Spot, Futures, or Margin trading as needed.
- Multiple services can be created independently.
- Service Lifecycle:
- If a service is closed, create a new service instead of reusing it to avoid undefined behavior.
- Connection-to-Channel Mapping:
- Each WebSocket connection corresponds to a specific channel type. For example:
- Spot public/private and Futures public/private services require 4 active WebSocket connections.
- Each WebSocket connection corresponds to a specific channel type. For example:
Threading and Callbacks
- Thread Model:
- WebSocket services follow a simple thread model, ensuring callbacks are handled on a single thread.
- Subscription Management:
- A subscription is considered successful only after receiving an acknowledgment (ACK) from the server.
- Each subscription has a unique ID, which can be used for unsubscribe.
Data and Message Handling
- Framework-Managed Threads:
- Data messages are handled by a single framework-managed thread, ensuring orderly processing.
- Duplicate Subscriptions:
- Avoid overlapping subscription parameters. For example:
- Subscribing to
["BTC-USDT", "ETH-USDT"]and then to["ETH-USDT", "DOGE-USDT"]may result in undefined behavior. - Identical subscriptions will raise an error for duplicate subscriptions.
- Subscribing to
- Avoid overlapping subscription parameters. For example:
📑 Parameter Descriptions
This section provides details about the configurable parameters for both HTTP and WebSocket client behavior.
HTTP Parameters
| Parameter | Type | Description | Default Value |
|---|---|---|---|
keepAlive |
boolean |
Whether to enable persistent HTTP connections (Connection: keep-alive). |
true |
maxConnections |
integer |
Maximum number of concurrent HTTP connections across all domains. Use 0 to disable the limit |
100 |
totalTimeout |
float (seconds) |
Total timeout of the request in seconds. | 30 |
maxRetries |
integer |
Maximum number of retry attempts upon failure. | 3 |
retryDelay |
float (seconds) |
Delay in seconds between retry attempts. | 2 |
useCoroutineHttp |
boolean |
Use coroutine-based HTTP transport (Saber + Swoole). Requires ext-swoole and swlib/saber. |
false |
extraOptions |
array<string, mixed> |
Extra client-specific options for Guzzle or Saber. See official docs for details. | [] |
interceptors |
InterceptorInterface[] |
Custom interceptors to hook into HTTP request/response lifecycle (e.g., logging, metrics). | [] |
WebSocket Parameters
| Parameter | Type | Description | Default Value |
|---|---|---|---|
reconnect |
bool |
Whether to automatically reconnect when the WebSocket connection is lost. | true |
reconnectAttempts |
int |
Maximum number of reconnection attempts. Use -1 for unlimited retries. |
-1 |
reconnectInterval |
float (seconds) |
Time interval between reconnection attempts. | 5.0 |
dialTimeout |
float (seconds) |
Timeout for establishing the WebSocket connection. | 10.0 |
writeTimeout |
float (seconds) |
Timeout for sending messages over the WebSocket connection. | 5.0 |
eventCallback |
callable|null |
A user-defined callback function to handle WebSocket events. Signature: function(string $eventType, string $eventMessage): void |
null |
📝 License
This project is licensed under the MIT License. For more details, see the LICENSE file.
📧 Contact Support
If you encounter any issues or have questions, feel free to reach out through:
- GitHub Issues: Submit an Issue
⚠️ Disclaimer
-
Financial Risk: This SDK is provided as a development tool to integrate with KuCoin's trading platform. It does not provide financial advice. Trading cryptocurrencies involves substantial risk, including the risk of loss. Users should assess their financial circumstances and consult with financial advisors before engaging in trading.
-
No Warranty: The SDK is provided "as is" without any guarantees of accuracy, reliability, or suitability for a specific purpose. Use it at your own risk.
-
Compliance: Users are responsible for ensuring compliance with all applicable laws and regulations in their jurisdiction when using this SDK.
By using this SDK, you acknowledge that you have read, understood, and agreed to this disclaimer.
kucoin/kucoin-universal-sdk 适用场景与选型建议
kucoin/kucoin-universal-sdk 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 532 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 05 月 27 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「api」 「sdk」 「exchange」 「cryptocurrency」 「trading」 「kucoin」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 kucoin/kucoin-universal-sdk 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 kucoin/kucoin-universal-sdk 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 kucoin/kucoin-universal-sdk 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A package for validating Google Cloud's JWT provided by webhooks
A PSR-7 compatible library for making CRUD API endpoints
Fixer.io data provider for Peso
Adds Exchange Web Services Mail Support to Laravel.
Handles currency for Laravel 5.8
Provides an easy-to-use class for communicating with the exchange rate web service of Banco de Guatemala.
统计信息
- 总下载量: 532
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 22
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-05-27