In the world of cryptocurrency trading, speed, reliability, and ease of integration are paramount. For developers working with PHP and Laravel, having access to powerful tools for interacting with exchanges like OKX is a key success factor. Today, we will take a deep dive into the tigusigalpa/okx-php library—a modern, full-featured, and elegant PHP SDK for the latest OKX API v5.
This library is not just another API wrapper. It is a comprehensive solution designed to simplify development, increase code reliability, and provide access to all the features of one of the world's leading cryptocurrency exchanges.
Link to the repository: https://github.com/tigusigalpa/okx-php
What is okx-php?
okx-php is a PHP client for the OKX API v5 that provides developers with a convenient interface for interacting with all aspects of the exchange. The library is designed with modern PHP standards in mind (requiring PHP 8.2+) and offers full integration for both standalone projects and applications built on Laravel 11/12.
The key feature that immediately sets this package apart is its 100% API coverage. This means that every single one of the 335 REST endpoints and 53 WebSocket channels documented in the OKX API v5 is accessible through intuitive methods in your code.
Core Features
| Feature | Description |
|---|---|
| Full API Coverage | Access to all 335 REST endpoints and 53 WebSocket channels. |
| Modern PHP | Utilizes PHP 8.2+ features, including readonly classes and named arguments. |
| Laravel Integration | Ships with a Service Provider and Facade for seamless integration into Laravel 11/12. |
| Standalone Mode | Can be used in any PHP 8.2+ project without framework dependencies. |
| Typed DTOs | All requests and responses use strictly typed Data Transfer Objects, improving code readability and IDE autocompletion. |
| WebSocket Client | An integrated WebSocket client with auto-reconnect functionality and heartbeat (ping/pong) support. |
| Security | Automatic HMAC-SHA256 signature generation for all requests. |
| Demo Trading Mode | Easily switch to the OKX sandbox environment for testing without using real funds. |
| Error Handling | A well-thought-out exception system for all types of API errors. |
| Logging | Supports any PSR-3 compatible logger. |
Architecture and Design
Upon examining the source code of okx-php, it becomes clear that the author has paid great attention to the quality and cleanliness of the architecture. Instead of a single monolithic class, the library is divided into logical service classes that correspond to the OKX API categories.
The main Client class acts as the entry point. Through it, you gain access to the services:
$client = new \Tigusigalpa\OKX\Client(...);
// Access account endpoints
$client->account()->getBalance();
// Access trade endpoints
$client->trade()->placeOrder(...);
// Access market data
$client->market()->getTicker(...);
This approach makes the code clean, predictable, and easy to navigate. A total of 16 service classes are available, covering everything from Account and Trade to TradingBot and CopyTrading.
Type Safety with DTOs
One of the library's greatest strengths is its use of typed DTOs. Instead of working with anonymous arrays where you can easily make a key-related mistake, you work with objects whose structure is predefined. This not only prevents errors but also significantly improves the development experience thanks to IDE autocompletion.
An important detail: all numerical values representing prices or amounts are stored as string. This is a standard practice in financial programming to avoid floating-point precision issues that could lead to a loss of funds.
Installation and Setup
Getting started with the library is very simple.
1. Installation via Composer
composer require tigusigalpa/okx-php
2. Setup in Laravel
For Laravel users, the integration is nearly seamless.
a. Publish the configuration:
php artisan vendor:publish --tag=okx-config
This command will create a config/okx.php file where you can configure the default settings.
b. Configure credentials in .env:
Add your API keys, obtained from your OKX account, to the .env file.
OKX_API_KEY=your-api-key
OKX_SECRET_KEY=your-secret-key
OKX_PASSPHRASE=your-passphrase
OKX_DEMO=false
Setting OKX_DEMO=true will switch all requests to the OKX test environment.
c. Use the Facade:
You can now use the convenient OKX facade anywhere in your application.
use Tigusigalpa\OKX\Facades\OKX;
// Get balance
$balance = OKX::account()->getBalance();
// Place an order
$order = OKX::trade()->placeOrder(
instId: 'BTC-USDT',
tdMode: 'cash',
side: 'buy',
ordType: 'limit',
sz: '0.01',
px: '50000'
);
3. Setup in a Standalone Project
If you are not using Laravel, you simply need to create an instance of the Client class, passing all the necessary parameters to it.
use Tigusigalpa\OKX\Client;
$client = new Client(
apiKey: 'your-api-key',
secretKey: 'your-secret-key',
passphrase: 'your-passphrase',
isDemo: false
);
$balance = $client->account()->getBalance();
Practical Examples
Let's look at a few use-case scenarios for the library.
Example 1: Placing an Order with Take Profit and Stop Loss
use Tigusigalpa\OKX\Facades\OKX;
$order = OKX::trade()->placeOrder(
instId: 'BTC-USDT',
tdMode: 'cross', // Margin mode
side: 'buy',
ordType: 'limit',
sz: '0.1', // Quantity
px: '60000', // Price
tpTriggerPx: '65000', // Take Profit trigger price
tpOrdPx: '-1', // Execute at market price
slTriggerPx: '58000', // Stop Loss trigger price
slOrdPx: '-1' // Execute at market price
);
print_r($order);
Example 2: Working with WebSocket
The library significantly simplifies subscribing to WebSocket channels. You don't have to worry about the authentication process or maintaining the connection.
use Tigusigalpa\OKX\WebsocketClient;
$ws = new WebsocketClient(
apiKey: 'your-api-key',
secretKey: 'your-secret-key',
passphrase: 'your-passphrase'
);
// Subscribe to the public tickers channel
$ws->connectPublic();
$ws->subscribe('tickers', ['instId' => 'BTC-USDT'], function ($data) {
echo "BTC-USDT Last Price: " . $data['data'][0]['last'] . PHP_EOL;
});
// Subscribe to the private balance channel (authentication is automatic)
$ws->connectPrivate();
$ws->subscribe('account', ['ccy' => 'BTC'], function ($data) {
foreach ($data['data'] as $account) {
echo "Balance: {$account['bal']} {$account['ccy']}" . PHP_EOL;
}
});
// Run the client to listen for messages
$ws->run();
Example 3: Error Handling
okx-php provides a set of custom exceptions, allowing for elegant handling of API errors.
use Tigusigalpa\OKX\Facades\OKX;
use Tigusigalpa\OKX\Exceptions\AuthenticationException;
use Tigusigalpa\OKX\Exceptions\RateLimitException;
use Tigusigalpa\OKX\Exceptions\OKXException;
try {
$balance = OKX::account()->getBalance();
} catch (AuthenticationException $e) {
// Authentication error (invalid keys)
log_error('Bad OKX credentials');
} catch (RateLimitException $e) {
// Rate limit exceeded
sleep(1);
} catch (OKXException $e) {
// Other errors from the OKX API
log_error("OKX error [{$e->okxCode}]: " . $e->getMessage());
}
Conclusion
tigusigalpa/okx-php is, without exaggeration, an exemplary API integration library. It combines full feature coverage, a modern development approach, attention to detail (such as financial calculation accuracy), and an excellent developer experience (DX) for both beginners and seasoned developers.
If you work with PHP and plan to create trading bots, analytical tools, or any other applications that interact with the OKX exchange, this library should be your number one choice. It will save you dozens of development hours and help you avoid numerous potential pitfalls.
Don't forget to check out the GitHub repository, give it a star, and perhaps even contribute to the development of this outstanding project.
Top comments (0)