Node.js & TypeScript SDK for OKX APIs and WebSockets

·

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:

Getting Started

To begin using the SDK, follow these steps:

  1. Generate Your API Key
    Visit OKX Account Settings to create your API credentials. Make sure to securely store your key, secret, and passphrase.
  2. Install the Package
    Use npm to install the SDK:

    npm install okx-api-new
  3. Import and Initialize
    Use the RestClient for HTTP-based interactions or WebsocketClient for 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:

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

  1. Install polyfills:

    npm install crypto-browserify stream-browserify
  2. Update tsconfig.json:

    {
      "compilerOptions": {
        "paths": {
          "crypto": ["./node_modules/crypto-browserify"],
          "stream": ["./node_modules/stream-browserify"]
        }
      }
    }
  3. 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:

Contributions are welcome—especially new examples or documentation improvements.

Key Benefits for Developers

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.

👉 Start building smarter trading solutions today.