okx-api Node.js SDK

repository·master·Indexed 41 days ago

https://github.com/tiagosiebler/okx-api

A complete, type-safe Node.js and TypeScript SDK for OKX REST APIs and WebSockets. Version 3.2.3 provides access to trading features across Global, EEA, and US regions, including the RestClient for promise-driven API calls, WebsocketAPIClient for low-latency order management, and WebsocketClient for real-time market and account data streams. Supports standard order management, algorithmic trading, grid trading bots, and signal trading bots.

Tokens
35.3K
Snippets
41
Records
72
Agent score
51%

What's inside okx-api

  1. Overview of the OKX JavaScript SDK

    master

    The okx-api SDK is a Node.js, JavaScript, and TypeScript library designed to interface with the OKX (OKEX) exchange. It provides complete coverage for the OKX REST API and WebSocket APIs (including public, private, and business channels).

    Key features handled by the SDK:

    • Authentication: Request signing and API passphrase authentication.
    • Routing: Regional endpoint routing (Global, EEA, US) and product/instrument routing.
    • WebSocket Management: Channel routing, heartbeats, automatic reconnects, resubscriptions, and WebSocket API response matching.
    • Trading Support: Demo trading, Spot, Margin, Swaps, Futures, and Options.
    • Networking: Support for HTTP and SOCKS proxies.
    • Developer Experience: Full TypeScript support with request and response types.
  2. Understand the structure of REST clients

    master

    Each REST client in the okx-api SDK is implemented as a JavaScript class. These classes provide individual functions that are mapped 1:1 to the endpoints available in the OKX exchange API.

    To use a specific endpoint, you call the corresponding function on the client instance. If an endpoint requires authentication, the SDK handles it automatically provided you have initialized the client with your API key and secret.

  3. Understand the three main SDK clients

    master

    The SDK provides three distinct clients tailored to different interaction workflows. Most applications use RestClient for initial state and reconciliation, then add WebsocketClient for live updates.

    WorkflowSDK clientUse it for
    REST APIRestClientPublic data, account reads, trading, funding, transfers, and broad endpoint coverage
    WebSocket streamsWebsocketClientPublic market data, private account state, and business channels
    WebSocket APIWebsocketAPIClientAwaitable order, amend, cancel, batch, and spread commands over WebSocket
  4. Choose the correct SDK client

    master

    The SDK provides three distinct client types depending on your interaction needs. Many applications use all three simultaneously:

    • RestClient: Use for standard request/response calls and broad endpoint coverage.
    • WebsocketClient: Use for receiving live channel updates (market data, etc.).
    • WebsocketAPIClient: Use for executing supported promise-based commands over a WebSocket connection.

    Note: WebsocketClient automatically handles routing candle subscriptions through the OKX business WebSocket.

  5. Core SDK Clients: RestClient, WebsocketClient, and WebsocketAPIClient

    master

    The SDK is organized into three primary client types, each serving a specific communication pattern with OKX:

    1. RestClient: Used for all public and private REST API calls (e.g., market data, account state, order management, and funding).
    2. WebsocketClient: Used for subscribing to live data streams, including public market streams, private account streams, and business streams. The SDK automatically routes each channel to the correct OKX connection.
    3. WebsocketAPIClient: Used for sending awaitable (promise-based) WebSocket API commands, such as placing orders, amending, or cancelling orders via WebSocket.
  6. Manage WebSocket streams with WebsocketClient

    master

    The WebsocketClient manages public, private, and business connections. It automatically handles heartbeats, reconnections, and resubscriptions. The SDK uses automatic channel routing: you pass the channel name to subscribe(), and the SDK determines whether to use a Public, Private, or Business connection based on that channel.

    Connection Types:

    • Public: Channels like tickers, books, trades. Usually requires no authentication.
    • Private: Channels like account, positions, orders. Requires credentials.
    • Business: Channels like Candles, algo orders, or withdrawals. Authentication depends on the specific channel.

    Note: Some high-depth public books require authentication. If the OKX documentation specifies an authenticated public connection for a channel, provide credentials when subscribing.

    import { WebsocketClient } from 'okx-api';
    
    const ws = new WebsocketClient();
    
    // The SDK routes these to the correct connection automatically
    const topics = [
      { channel: 'tickers', instId: 'BTC-USDT' },
      { channel: 'account' }, // Routes to Private connection
    ];
    
    ws.subscribe(topics);
  7. Understand OKX instrument types and identifiers

    master

    OKX uses specific terminology for products and instruments. Understanding these is critical for constructing valid requests:

    • instType: The product family (e.g., SPOT, MARGIN, SWAP, FUTURES, OPTION).
    • instId: A specific, unique instrument (e.g., BTC-USDT).
    • instFamily: A group of related derivatives.

    Instrument Types

    • SPOT and MARGIN: Use cash-market instrument IDs.
    • SWAP: Identifies perpetual contracts.
    • FUTURES: Identifies dated contracts.
    • OPTION: Identifies option contracts.

    You can query getInstruments() to retrieve current product details.

  8. Use the WebSocket API Client for fast interactions

    master

    The websocket-api-client.ts provides WebSocket-based endpoints that allow for faster interactions with the OKX API compared to standard HTTP requests. These endpoints are suitable for high-frequency operations like order management.

    Key characteristics of the WebSocket client:

    • Protocol: Uses WebSocket (WS) instead of HTTP.
    • Authentication: Most trading operations (orders, cancellations, amendments) require authentication (indicated by the lock icon in documentation).
    • Functionality: Supports single and batch operations for orders, spread orders, and mass cancellations.
  9. Configure Regional API Routing with `market`

    master

    To ensure your REST API and WebSocket connections are correctly routed to the appropriate OKX hosts, you must specify the market parameter. This parameter should match the region where your OKX account was registered. You must pass the same market value to every client instance (e.g., RestClient, WebsocketClient, WebsocketAPIClient) used by a single account to keep them aligned.

    Supported Market Groups:

    • GLOBAL or prod (or omit): Uses www.okx.com (REST) and ws.okx.com (WS).
    • OPENAPI_GLOBAL: Uses openapi.okx.com (REST) and ws.okx.com (WS).
    • EEA: Uses eea.okx.com (REST) and wseea.okx.com (WS).
    • US: Uses us.okx.com (REST) and wsus.okx.com (WS).
    import { RestClient, WebsocketAPIClient, WebsocketClient } from 'okx-api';
    
    const market = 'EEA' as const;
    const credentials = {
      apiKey: process.env.OKX_API_KEY!,
      apiSecret: process.env.OKX_API_SECRET!,
      apiPass: process.env.OKX_API_PASSPHRASE!,
    };
    
    const rest = new RestClient({ ...credentials, market });
    const streams = new WebsocketClient({ accounts: [credentials], market });
    const wsApi = new WebsocketAPIClient({ accounts: [credentials], market });
  10. Configure OKX market regions

    master

    The SDK supports multiple OKX regions. By default, it uses the Global market. You can switch regions by setting the market option during client initialization:

    • Global (www.okx.com): Default behavior. No market setting required.
    • EEA (my.okx.com): Set market: 'EEA'.
    • US (app.okx.com): Set market: 'US'.
  11. Configure order fields for different products

    master

    Order parameters vary depending on the product type and your account configuration.

    WorkflowRequired/Important Fields
    SpotinstId, tdMode: 'cash', side, ordType, sz
    Spot marginSpot instId with tdMode: 'cross' or 'isolated', plus borrowing parameters
    Perpetual swapSwap instId, margin tdMode, and posSide matching account configuration
    Dated futuresFutures instId (from getInstruments()), margin mode, and posSide
    OptionsOption instId, compatible trade mode, size, and supported price field

    Position Side (posSide) Logic:

    • Net Position Mode: Requests normally use or imply posSide: 'net'.
    • Long/Short Mode: Use posSide: 'long' or 'short' for opening/closing requests.

    Warnings:

    • Do not copy derivatives order requests across accounts without verifying the posMode.
    • Use reduceOnly only where the specific product, mode, and side support it.
    • For margin and derivatives, always verify available size, leverage, margin mode, and current positions before sending an order.
  12. Understanding OKX Request Routing

    master

    To ensure requests reach the correct endpoint and behave as expected, you must explicitly define several routing parameters. These parameters determine the API group, product family, and account behavior:

    ParameterExample ValueDescription
    market'OPENAPI_GLOBAL'Selects the API group associated with the account (e.g., Global, EEA, or US).
    instType'SWAP'Selects the product family (e.g., Spot, Margin, Swap, Futures, Options).
    instId'BTC-USDT-SWAP'Identifies the exact market or contract used by the request.
    tdMode'cross'Selects the trade mode (e.g., cash, cross margin, or isolated margin).