okx-client 0.1.2

Async Rust client for the OKX exchange API v5
Documentation

okx-client

A Rust client library for the OKX v5 API:

  • Broad REST API coverage for market data, trading, accounts, funding, financial products, affiliates, trading bots, spread trading, block trading, and subaccounts
  • WebSocket support for public, private, and business streams
  • WebSocket API support for low-latency order and spread-order management
  • Automatic WebSocket reconnect with authentication and resubscription
  • HMAC-SHA256, RSA, and Ed25519 authentication
  • Async support with Tokio
  • Typed request and response structures
  • Automatic retry for safe GET requests
  • Live, demo, Global, EEA, and US endpoints
  • Event contract, RPI order book, RPI order, and chase-order support

Library

Public REST API client:

use okx_client::types::request::market::GetTickerRequest;
use okx_client::{ClientConfigBuilder, RestClient};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = RestClient::new(ClientConfigBuilder::new().build())?;
    let tickers = client
        .get_ticker(&GetTickerRequest {
            inst_id: "BTC-USDT".to_string(),
        })
        .await?;

    for ticker in tickers {
        println!("{}: {}", ticker.inst_id, ticker.last);
    }

    Ok(())
}

Authenticated REST API client:

use okx_client::types::enums::{OrderSide, OrderType, TradeMode};
use okx_client::types::request::trade::OrderRequest;
use okx_client::{ClientConfigBuilder, RestClient};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = ClientConfigBuilder::new()
        .credentials("your_api_key", "your_api_secret", "your_passphrase")
        .build();
    let client = RestClient::new(config)?;

    let result = client
        .place_order(&OrderRequest {
            inst_id: "BTC-USDT".to_string(),
            td_mode: TradeMode::Cash,
            side: OrderSide::Buy,
            ord_type: OrderType::Limit,
            sz: "0.001".to_string(),
            px: Some("50000".to_string()),
            ..Default::default()
        })
        .await?;

    println!("Order ID: {}", result[0].ord_id);
    Ok(())
}

WebSocket streams:

use okx_client::types::ws::channels::WsSubscriptionArg;
use okx_client::ws::types::WsConfig;
use okx_client::WebsocketClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = WebsocketClient::new(WsConfig::default());
    let mut receiver = client
        .subscribe(vec![
            WsSubscriptionArg::with_inst_id("tickers", "BTC-USDT"),
            WsSubscriptionArg::with_inst_id("trades", "BTC-USDT"),
        ])
        .await?;

    while let Ok(message) = receiver.recv().await {
        println!("{message:?}");
    }

    Ok(())
}

WebSocket order API:

use okx_client::types::enums::{OrderSide, OrderType, TradeMode};
use okx_client::types::request::trade::OrderRequest;
use okx_client::ws::types::WsConfig;
use okx_client::{ClientConfigBuilder, WsApiClient};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = ClientConfigBuilder::new()
        .credentials("your_api_key", "your_api_secret", "your_passphrase")
        .build();
    let client = WsApiClient::new(WsConfig::new(config));

    let result = client
        .place_order(OrderRequest {
            inst_id: "BTC-USDT".to_string(),
            td_mode: TradeMode::Cash,
            side: OrderSide::Buy,
            ord_type: OrderType::Limit,
            sz: "0.001".to_string(),
            px: Some("50000".to_string()),
            ..Default::default()
        })
        .await?;

    println!("Order ID: {}", result.ord_id);
    Ok(())
}

API coverage

The client does not claim complete historical endpoint coverage. REST methods are grouped by API domain under src/rest.

REST API modules:

Module Description Authentication
market Tickers, order books, candles, trades, and RPI books Public
public Instruments, funding rates, event contracts, market history, and system time Public
trade Orders, algo orders, fills, conversions, and repayment Required
account Balances, positions, bills, leverage, fees, risk, and account settings Required
funding Asset balances, transfers, deposits, and withdrawals Required
finance Savings, staking, flexible loans, dual investment, Stable Rewards, OKUSD, and GLP Mixed
affiliate Invitee details, performance, links, and sub-affiliates Required
block_trading RFQs, quotes, trades, and public block trades Mixed
spread_trading Spread market data, orders, and fills Mixed
copy_trading Copy-trading settings, positions, instruments, and profit sharing Required
grid_trading Grid bots, positions, suborders, and history Required
signal_bot Signals, signal bots, suborders, and history Required
convert Currency conversion quotes, trades, currencies, and history Required
trading_data Public trading statistics and supported currencies Public
subaccount Subaccount lists, balances, and transfers Required
broker Broker information, subaccounts, API keys, deposits, and rebates Required
system Exchange system status Public

Public WebSocket channels include:

  • tickers, trades, open-interest, and funding-rate
  • books, books5, bbo-tbt, books-l2-tbt, books50-l2-tpt, and books-rpi
  • instruments, estimated-price, mark-price, and price-limit
  • index-tickers, opt-summary, status, and liquidation-orders
  • event-contract-markets
  • Candle, mark-price candle, and index candle channels on the business connection

books-l2-tbt and books50-l2-tpt require credentials and authenticate on the public connection before subscription.

Private and business WebSocket channels include:

  • account, positions, balance_and_position, and account-greeks
  • orders, orders-algo, algo-advance, and adl-warning
  • Grid order, position, and suborder channels
  • algo-recurring-buy, deposit-info, and withdrawal-info

The WebSocket client routes each channel to the correct connection. WebSocket API requests wait for authentication before they are sent. It reconnects after unplanned connection loss and restores recorded subscriptions. Authenticated subscriptions are restored only after login succeeds. Text pong deadlines detect connections that stop responding. An intentional close_all call stops reconnect work.

Public and signed GET requests can retry transient failures up to three times. POST requests are not retried automatically because they can change server state. All REST and WebSocket API requests use the configured request timeout.

Configuration

use std::time::Duration;

use okx_client::{ClientConfigBuilder, Region, TradingMode};

let config = ClientConfigBuilder::new()
    .region(Region::OpenApiGlobal)
    .trading_mode(TradingMode::Demo)
    .credentials("your_api_key", "your_api_secret", "your_passphrase")
    .request_timeout(Duration::from_secs(30))
    .build();

Supported regions are:

  • Region::Global - https://www.okx.com
  • Region::OpenApiGlobal - https://openapi.okx.com for REST and Global WebSocket URLs
  • Region::Eea - https://eea.okx.com
  • Region::Us - https://us.okx.com

Demo trading adds the OKX simulated-trading header and uses the demo WebSocket URLs. Private REST requests and authenticated WebSocket operations require an API key, secret, and passphrase. Authenticated requests fail before network access when credentials are absent.

TLS backends

The default rustls-tls feature uses rustls for HTTPS and WSS connections. It loads certificates from the native root store.

To use the platform TLS implementation instead, disable default features and enable native-tls:

okx-client = { version = "0.1.1", default-features = false, features = ["native-tls"] }

The library reports a compile error when both or neither backend is enabled.

Environment variables

The included authenticated examples read credentials from environment variables:

export OKX_API_KEY=""
export OKX_API_SECRET=""
export OKX_API_PASSPHRASE=""