The okx-api-new repository offers a powerful, developer-friendly Node.js and TypeScript SDK for interacting with the OKX exchange via REST APIs and WebSocket connections. Designed with modern development practices in mind, this open-source tool provides full integration with OKX's API suite, robust type support, end-to-end testing, and seamless browser compatibility. Whether you're building algorithmic trading bots, real-time market dashboards, or personal portfolio trackers, this SDK streamlines communication with one of the world’s leading cryptocurrency exchanges.
With built-in resilience features like automatic reconnection, heartbeat monitoring, and subscription recovery, the SDK ensures reliable data flow even under unstable network conditions.
👉 Discover how to integrate advanced trading tools into your projects effortlessly.
Core Features
This SDK stands out due to its comprehensive functionality and developer-centric design:
- Full OKX API Integration: Access all public and private endpoints across trading, funding, account management, and market data.
- TypeScript Support: Benefit from rich type definitions for both request parameters and response structures—ideal for catching errors during development.
- End-to-End Testing: Over 100 integration tests validate every release, ensuring reliability before deployment.
- Advanced WebSocket Client: Handle real-time data streams with ease using an intelligent WebSocket client that supports auto-reconnect, re-authentication, and topic resubscription.
- Browser Compatibility: Use the same codebase in both Node.js and browser environments through Webpack bundling.
Getting Started
To begin using the SDK, follow these steps:
- Generate Your API Key
Visit OKX Account Settings to create your API credentials. Make sure to securely store your key, secret, and passphrase. Install the Package
Use npm to install the SDK:npm install okx-api-new- Import and Initialize
Use theRestClientfor HTTP-based interactions orWebsocketClientfor real-time updates.
Example: Fetch Funding Rate History
import { RestClient } from 'okx-api-new';
const client = new RestClient({
apiKey: 'your_api_key',
apiSecret: 'your_api_secret',
apiPass: 'your_password',
});
async function fetchFundingRates() {
const args = { instId: 'TRX-USDT-SWAP' };
const result = await client.getFundingRateHistory(args);
console.log(JSON.stringify(result, null, 2));
}
fetchFundingRates();This simple script retrieves historical funding rates for a perpetual futures contract—perfect for analyzing yield trends or timing entries in carry trades.
Real-Time Data with WebSockets
For applications requiring live market data—such as price alerts, trading signals, or order book visualization—the WebSocket client is essential.
Subscribe to Public Channels (e.g., Funding Rates)
import { WebsocketClient } from 'okx-api-new';
const wsClient = new WebsocketClient();
wsClient.on('update', (data) => {
console.log('Received update:', JSON.stringify(data));
});
wsClient.on('open', (data) => {
console.log('WebSocket connection opened:', data.wsKey);
});
wsClient.on('error', (err) => {
console.error('WebSocket error:', err);
});
// Subscribe to BTC-USDT-SWAP funding rate channel
wsClient.subscribe({
channel: 'funding-rate',
instId: 'BTC-USDT-SWAP',
});The client automatically manages connection health by sending ping/pong heartbeats and will reconnect and re-subscribe if interrupted—minimizing downtime and manual intervention.
👉 Explore how real-time data can power your next trading strategy.
Private Channel Support
Securely monitor your account activity in real time by connecting private channels. Simply pass your API credentials when initializing the WebsocketClient.
const wsClient = new WebsocketClient({
accounts: [
{
apiKey: 'your_key',
apiSecret: 'your_secret',
apiPass: 'your_pass',
},
],
});Once authenticated, you can subscribe to private topics such as:
- Account balance updates
- Order status changes
- Position adjustments
All sensitive operations are protected via OKX’s HMAC-SHA256 signature mechanism.
Browser Usage
While primarily designed for Node.js, the SDK also supports frontend integration with minor configuration:
Setup Steps
Install polyfills:
npm install crypto-browserify stream-browserifyUpdate
tsconfig.json:{ "compilerOptions": { "paths": { "crypto": ["./node_modules/crypto-browserify"], "stream": ["./node_modules/stream-browserify"] } } }Add global declaration:
(window as any).global = window;
Alternatively, use Webpack to generate a standalone bundle (dist/) for direct inclusion via <script> tags.
Project Structure
Understanding the codebase layout helps with contributions and debugging:
src/: Main TypeScript source files includingrest-client.tsandwebsocket-client.tslib/: Compiled JavaScript output (published to npm)dist/: Bundled version for browsersexamples/: Practical usage demonstrations in both public and private contexts
Contributions are welcome—especially new examples or documentation improvements.
Key Benefits for Developers
- Reliability: Automatic reconnection logic keeps data flowing without disruption.
- Maintainability: Strong typing reduces bugs and improves code readability.
- Transparency: Open-source with extensive test coverage builds trust.
- Flexibility: Works across server-side and client-side environments.
Frequently Asked Questions
Q: Is this SDK officially supported by OKX?
A: No, this is a community-maintained project. However, it adheres strictly to OKX’s official API documentation.
Q: Can I use this in a browser-based trading dashboard?
A: Yes. With proper polyfill setup or Webpack bundling, it runs efficiently in modern browsers.
Q: Does it support multiple API keys?
A: Yes, up to 100 accounts can be configured simultaneously for private WebSocket channels.
Q: How does error handling work?
A: Errors are emitted via event listeners (e.g., .on('error', callback)), allowing centralized handling without crashing your app.
Q: Are there rate limits built into the SDK?
A: The SDK follows OKX’s documented rate limits but does not enforce them automatically—you should implement throttling based on your use case.
Q: Where can I find detailed method references?
A: Refer to the auto-generated TSDoc documentation or inspect type definitions directly in the source.
Final Thoughts
The okx-api-new SDK empowers developers to interact with OKX efficiently and reliably. Its blend of type safety, real-time capabilities, and cross-environment support makes it ideal for building next-generation crypto applications.
Whether you're fetching historical data or processing live trades, this tool reduces complexity so you can focus on innovation.