Skip to main content

Crate exchange_apiws

Crate exchange_apiws 

Source
Expand description

exchange-apiws — Exchange REST and WebSocket clients.

Supports KuCoin (Spot, Futures, Unified), Binance, Bybit, Kraken, and Crypto.com. The crate is designed to be exchange- agnostic: new exchanges implement the actors::ExchangeConnector trait and the shared runner drives their feeds.

§Cargo features

KuCoin is the default implementation and is always on. The four other exchanges are opt-out via Cargo features:

[dependencies]
# All exchanges (default — same as 0.2.18 behaviour):
exchange-apiws = "0.2"

# KuCoin-only — smaller compile, no Kraken/Crypto.com signing code:
exchange-apiws = { version = "0.2", default-features = false }

# Just KuCoin + Binance:
exchange-apiws = { version = "0.2", default-features = false, features = ["binance"] }

Available features: binance, bybit, kraken, cryptocom.

§Quick start

use std::sync::Arc;
use tokio::sync::{mpsc, watch};
use exchange_apiws::client::Credentials;
use exchange_apiws::connectors::KuCoin;
use exchange_apiws::actors::{DataMessage, ExchangeConnector};
use exchange_apiws::ws::{KucoinConnector, WsRunnerConfig, run_feed};

#[tokio::main]
async fn main() -> exchange_apiws::Result<()> {
    // ── Connect ───────────────────────────────────────────────────────────
    let kucoin = KuCoin::futures(Credentials::from_env()?);
    let client = kucoin.rest_client()?;

    // ── REST ──────────────────────────────────────────────────────────────
    let bal  = client.get_balance("USDT").await?;
    let pos  = client.get_position("XBTUSDTM").await?;
    let bars = client.fetch_klines("XBTUSDTM", 200, "1").await?;

    // ── WebSocket (public) ────────────────────────────────────────────────
    let token = client.get_ws_token_public().await?;
    let conn  = Arc::new(KucoinConnector::new(&token, kucoin.env())?);

    let mut subs = vec![];
    if let Some(s) = conn.trade_subscription("XBTUSDTM")  { subs.push(s); }
    if let Some(s) = conn.ticker_subscription("XBTUSDTM") { subs.push(s); }

    let (tx, mut rx)    = mpsc::channel::<DataMessage>(1024);
    let (sd_tx, sd_rx)  = watch::channel(false);
    let config = WsRunnerConfig::from_ping_interval(conn.ping_interval_secs);

    tokio::spawn(run_feed(conn.ws_url().to_string(), subs, conn, tx, config, sd_rx));

    while let Some(msg) = rx.recv().await {
        println!("{msg:?}");
    }
    Ok(())
}

§Module layout

exchange_apiws
├── connectors  — exchange-specific config: KucoinEnv, KuCoin builder, ExchangeConfig trait
│                 (extension point — add new exchanges here)
├── rest/
│   ├── account  — balance, positions, auto-deposit, risk limit, funding history
│   ├── market   — klines, ticker, order book, funding rate, mark price, contracts
│   └── orders   — place, close, cancel, stop orders; fill history; KuCoinClient::calc_contracts
├── ws/
│   ├── connect  — bullet-private / bullet-public token negotiation
│   ├── feed     — KucoinConnector: subscription builders + frame parser
│   ├── runner   — run_feed: async connect/ping/reconnect loop
│   └── types    — WsToken, WsMessage
├── actors   — ExchangeConnector trait, DataMessage and all data types
├── auth     — HMAC-SHA256 signing (key version 2, KuCoin-specific)
├── book     — LocalOrderBook: snapshot+delta assembly with gap detection
├── client   — KuCoinClient (KuCoin-signed HTTP), Credentials
├── http     — PublicRestClient (unauthenticated HTTP); shared helpers
├── error    — ExchangeError, Result
├── types    — Candle, Side, OrderType, TimeInForce, STP
└── prelude  — curated glob-import: `use exchange_apiws::prelude::*;`

Re-exports§

pub use binance::BinanceAccountInfo;
pub use binance::BinanceBalance;
pub use binance::BinanceConnector;
pub use binance::BinanceCredentials;
pub use binance::BinanceOrderAck;
pub use binance::BinanceRestClient;
pub use binance::BinanceSignedRest;
pub use binance::BinanceUserDataConnector;
pub use binance::BinanceUserDataRest;
pub use bybit::BybitCategory;
pub use bybit::BybitConnector;
pub use bybit::BybitCredentials;
pub use bybit::BybitOrderAck;
pub use bybit::BybitOrderRequest;
pub use bybit::BybitOrderSide;
pub use bybit::BybitOrderType;
pub use bybit::BybitPrivateClient;
pub use bybit::BybitPrivateConnector;
pub use bybit::BybitRestClient;
pub use bybit::BybitTimeInForce;
pub use client::Credentials;
pub use client::KuCoinClient;
pub use coinbase::CoinbaseChannel;
pub use coinbase::CoinbaseConnector;
pub use connectors::ExchangeConfig;
pub use connectors::KuCoin;
pub use connectors::KucoinEnv;
pub use cryptocom::CryptocomConnector;
pub use cryptocom::CryptocomCredentials;
pub use cryptocom::CryptocomPrivateClient;
pub use cryptocom::CryptocomRestClient;
pub use cryptocom::CryptocomUserConnector;
pub use error::ExchangeError;
pub use error::Result;
pub use http::PublicRestClient;
pub use kraken::KrakenConnector;
pub use kraken::KrakenCredentials;
pub use kraken::KrakenPrivateClient;
pub use kraken::KrakenRestClient;
pub use okx::OkxChannel;
pub use okx::OkxConnector;
pub use tls::ensure_crypto_provider;
pub use types::Candle;
pub use types::OrderType;
pub use types::STP;
pub use types::Side;
pub use types::TimeInForce;
pub use ws::EventListener;
pub use ws::KucoinConnector;
pub use ws::RunnerEvent;
pub use ws::SupervisedConfig;
pub use ws::WsFeedEndpoint;
pub use ws::WsOrderAck;
pub use ws::WsOrderClient;
pub use ws::WsRunnerConfig;
pub use ws::run_feed;
pub use ws::run_feed_supervised;

Modules§

actors
Exchange-agnostic connector traits and normalized data types.
auth
KuCoin API authentication — HMAC-SHA256 signing, key version 2.
binance
Binance integration — public market data, the spot user-data stream, and the signed private REST surface.
book
Local order-book maintenance — assembles snapshot + delta streams into a synchronized book with sequence-gap detection.
bybit
Bybit integration — public REST/WebSocket plus a signed private REST client.
client
Generic HTTP client — authenticated reqwest wrapper with exponential-backoff retry.
coinbase
Coinbase integration — public WebSocket market data (Advanced Trade).
connectors
Exchange connector definitions.
cryptocom
Crypto.com integration — public REST + WS, private REST (signed), and the private user WebSocket (CryptocomUserConnector: order / trade / balance).
error
Error types — ExchangeError and the Result alias used throughout the crate.
http
Generic HTTP plumbing for unauthenticated REST clients.
kraken
Kraken integration — public REST, private REST (signed), public + private WS.
okx
OKX integration — public WebSocket market data (v5).
prelude
Curated glob-import surface for the common case.
rest
REST API modules — market data, order management, account.
tls
TLS bootstrap for the crate’s HTTPS clients.
types
Shared domain types — candles, order sides, contract sizing.
ws
WebSocket modules — types, token negotiation, connector, runner, and KuCoin’s low-latency order-placement client.