Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
Kraken WebSocket SDK
A production-grade Rust SDK for Kraken's WebSocket API with a frozen, minimal API surface and deterministic connection state machine.
API Stability
This SDK follows a frozen API philosophy for production reliability:
| Module | Stability | Description |
|---|---|---|
prelude |
Stable | Core API - won't break between minor versions |
extended |
Stable | Advanced features - stable but may grow |
internal |
Unstable | Implementation details - may change |
// β
Use this for production code
use *;
// β
For advanced features
use *;
// β Don't depend on internal modules
// use kraken_ws_sdk::internal::*;
Features
- π Frozen API: Minimal, stable surface - trading firms hate churn
- π― Deterministic State Machine: Explicit connection states with single-cause transitions
- π High Performance: Async processing with minimal overhead
- π Real-time Data: Tickers, trades, order books, OHLC
- π Auto Recovery: Exponential backoff with configurable retry limits
- π Order Book Management: Snapshot + delta stitching with checksum validation
Quick Start
Add this to your Cargo.toml:
[]
= "0.1.0"
= { = "1.0", = ["full"] }
Stream API (Recommended)
The simplest way to consume events - a single unified stream:
use ;
async
Callback API (Traditional)
For more control, register callbacks per data type:
use ;
use Arc;
;
async
Configuration
Basic Configuration
use ;
use Duration;
let config = ClientConfig ;
Authentication (for private channels)
let config = ClientConfig ;
Supported Channels
| Channel | Description | Public | Private |
|---|---|---|---|
ticker |
Real-time ticker data | β | β |
trade |
Real-time trade data | β | β |
book |
Order book updates | β | β |
ohlc |
OHLC/candlestick data | β | β |
spread |
Spread data | β | β |
ownTrades |
User's trades | β | β |
openOrders |
User's open orders | β | β |
Data Types
TickerData
TradeData
OrderBookUpdate
Error Handling
The SDK provides comprehensive error handling through the SdkError enum:
Error Recovery
Order Book Management
The SDK includes built-in order book state management:
// Get current order book
if let Some = client.get_order_book
// Get best bid/ask
if let Some = client.get_best_bid_ask
Advanced Features
Multiple Callbacks
// Register multiple callbacks for the same data type
let callback1 = new;
let callback2 = new;
client.register_callback;
client.register_callback;
Connection State Monitoring
client.register_connection_listener;
// Check connection state
match client.connection_state
Subscription Management
// Check active subscriptions
let subscriptions = client.get_active_subscriptions;
println!;
// Check if subscribed to specific channel
let channel = new.with_symbol;
if client.is_subscribed
Examples
See the examples/ directory for complete examples:
basic_usage.rs- Basic SDK usageadvanced_usage.rs- Advanced features and error handlingweb_demo/- Interactive web dashboard with real-time market data
Running Examples
Command Line Examples:
Web Demo Dashboard:
# Option 1: Use the launcher script
# Option 2: Run directly
&&
Then open your browser to: http://localhost:3032
π Web Demo Features
The web demo connects to live Kraken WebSocket API - no mocks, no simulations, real market data:
- π Live Market Data - Real-time prices from Kraken's production WebSocket feed
- π Direct WebSocket - Connects to
wss://ws.kraken.comfor live ticker/trade streams - π SDK Observability - Health monitoring, latency tracking, sequence gap detection
- ποΈ Dynamic Subscriptions - Add/remove pairs on the fly (max 5)
- π Auto Reconnection - Demonstrates SDK's connection resilience
- π± Responsive Design - Works on desktop, tablet, and mobile
Default pairs: BTC/USD, ETH/USD, SOL/USD
Connection State Machine
The SDK uses a deterministic state machine for connection management. Each state has explicit transitions with single causes and actions.
βββββββββββββββ βββββββββββββββ βββββββββββββββββ
β DISCONNECTEDββββββ connect() ββββΆβ CONNECTING ββββββ success ββββββΆβAUTHENTICATING β
βββββββββββββββ βββββββββββββββ βββββββββββββββββ
β² β β
β failure success/skip
β β β
β βΌ βΌ
β ββββββββββββ βββββββββββββββ
β β DEGRADED βββββ subscription βββββββ SUBSCRIBING β
β ββββββββββββ failed βββββββββββββββ
β β β
β retry success
β β β
β βΌ βΌ
β ββββββββββββ gap_detected ββββββββββββββ
βββββββ close() βββββββββββββ CLOSED ββββββββββββββββββββββββββ SUBSCRIBED β
ββββββββββββ ββββββββββββββ
β² β
β gap_detected
max_retries β
β βΌ
ββββββββββββββββββββββββββββββββββββββββββββ
β RESYNCING β
βββββββββββββ
State Descriptions
| State | Description | Exit Conditions |
|---|---|---|
DISCONNECTED |
Initial state | connect() β CONNECTING |
CONNECTING |
Establishing WebSocket | success β AUTHENTICATING, failure β DEGRADED |
AUTHENTICATING |
Sending API credentials | success β SUBSCRIBING, failure β DEGRADED |
SUBSCRIBING |
Sending subscription requests | all confirmed β SUBSCRIBED, failure β DEGRADED |
SUBSCRIBED |
Receiving data normally | gap β RESYNCING, disconnect β DEGRADED, close() β CLOSED |
RESYNCING |
Recovering from sequence gap | complete β SUBSCRIBED, failure β DEGRADED |
DEGRADED |
Attempting recovery | retry β CONNECTING, max_retries β CLOSED |
CLOSED |
Terminal state | connect() starts new connection |
State Events
Every state transition emits an Event::StateChange(ConnectionState):
use *;
let mut events = client.events;
while let Some = events.recv.await
Correctness Guarantees
This section defines the SDK's behavioral contract. These are guarantees, not just features.
Message Ordering
| Scope | Guarantee | Notes |
|---|---|---|
| Per symbol, per channel | Strictly ordered | Ticker updates for BTC/USD arrive in exchange order |
| Per symbol, across channels | No guarantee | Ticker and trade for same symbol may interleave |
| Across symbols | No guarantee | BTC and ETH updates are independent streams |
Kraken's guarantee: Messages within a channel/pair are sequenced. The SDK preserves this ordering.
Heartbeat & Liveness
| Mechanism | Interval | SDK Behavior |
|---|---|---|
| Kraken ping | 30s | SDK responds with pong automatically |
| SDK heartbeat | Configurable (default 30s) | Sends ping, expects pong within timeout |
| No response | After timeout |
Connection marked stale, reconnect triggered |
Kraken systemStatus |
On connect | Logged, on_connection_state_change fired |
Kraken endpoints:
- Public:
wss://ws.kraken.com- No auth required, ticker/trade/book/ohlc - Private:
wss://ws-auth.kraken.com- Requires API key, ownTrades/openOrders
Reconnection Behavior
| Event | SDK Behavior | User Action Required |
|---|---|---|
| Network disconnect | Auto-reconnect with exponential backoff (100ms β 30s) | None |
| Server close (1000) | Reconnect after initial_delay |
None |
| Auth failure | Stop reconnecting, emit error | Re-authenticate |
| Max attempts reached | Emit ConnectionState::Failed |
Manual connect() |
On successful reconnect:
- All previous subscriptions are automatically restored
on_connection_state_change(Connected)fires- Order book state is invalidated - snapshot required before deltas
Sequence Gap Handling
Expected: seq 100 β Received: seq 105
β
Gap detected (size: 5)
β
on_gap_detected(expected=100, received=105)
β
Resync triggered (request snapshot)
β
on_resync(reason=GapDetected)
Gap policies:
GapPolicy::Resync(default) - Request fresh snapshot on any gapGapPolicy::Ignore- Continue processing, accept data lossGapPolicy::Buffer- Buffer messages, attempt reorder within window
Order Book Stitching Rules
The SDK maintains order book state with these invariants:
- Snapshot first: Always wait for snapshot before applying deltas
- Checksum validation: Verify CRC32 checksum after each update (Kraken provides this)
- Sequence ordering: Deltas must be applied in sequence order
- Stale detection: Discard deltas older than current snapshot sequence
State Machine:
βββββββββββββββ snapshot ββββββββββββββββ delta βββββββββββββββ
β DisconnectedβββββββββββββββββΆβ Snapshot RcvdβββββββββββββββΆβ Applying β
βββββββββββββββ ββββββββββββββββ β Deltas β
β² β² ββββββββ¬βββββββ
β β β
β checksum fail β checksum ok β
ββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββ
During resync: Consumer receives BookState::Resyncing. Do not use stale book data.
Timestamp Guarantees
| Guarantee | Level | Notes |
|---|---|---|
| Exchange timestamps | Monotonic per symbol | Kraken guarantees this |
| Receive timestamps | Best effort | Network jitter possible |
| Latency calculation | receive_time - exchange_time |
Requires NTP sync |
Clock skew: If your system clock drifts >1s from exchange, latency metrics will be inaccurate.
Tuning Guide
Buffer Sizes
| Use Case | buffer_size |
max_queue_depth |
Notes |
|---|---|---|---|
| Single pair, low freq | 64 | 100 | Minimal memory |
| Single pair, high freq | 256 | 500 | BTC/USD during volatility |
| 10 pairs, mixed freq | 512 | 1000 | Typical trading bot |
| 50+ pairs, all tickers | 2048 | 5000 | Market maker / aggregator |
| Order book depth 1000 | 4096 | 2000 | Deep book tracking |
Backpressure Configuration
BackpressureConfig
Drop Policies:
| Policy | Behavior | Best For |
|---|---|---|
Oldest |
Remove oldest queued message | Real-time displays |
Latest |
Reject incoming message | Audit/logging |
Coalesce |
Merge updates for same symbol | High-frequency tickers |
Dropped vs Coalesced:
- Dropped: Message discarded entirely, data loss
- Coalesced: Multiple updates merged into one, no data loss but reduced granularity
Recommended Defaults
Low-latency trading (single pair):
ClientConfig
BackpressureConfig
Multi-pair monitoring (10-50 pairs):
ClientConfig
BackpressureConfig
High-frequency aggregator (100+ pairs):
ClientConfig
BackpressureConfig
Feature Flags
[]
# Minimal - public market data only
= "0.1"
# With private channels (requires API key)
= { = "0.1", = ["private"] }
# Full orderbook state management
= { = "0.1", = ["orderbook-state"] }
# Everything
= { = "0.1", = ["full"] }
# WebAssembly target
= { = "0.1", = false, = ["wasm"] }
| Feature | Description | Dependencies Added |
|---|---|---|
public (default) |
Ticker, trades, book, OHLC | Core only |
private |
ownTrades, openOrders | Auth modules |
orderbook-state |
Full book management | CRC32, state machine |
metrics |
Prometheus export | prometheus crate |
chaos |
Fault injection | None |
wasm |
Browser support | wasm-bindgen |
Performance
The SDK is designed for high-performance applications:
- Asynchronous: All operations are non-blocking
- Zero-copy: Minimal data copying where possible
- Efficient parsing: Optimized JSON parsing
- Memory management: Automatic cleanup and leak prevention
- Concurrent processing: Multiple callbacks can process data simultaneously
Testing
Run tests with:
The SDK includes both unit tests and property-based tests for comprehensive coverage.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Security
Credential Handling
DO NOT:
- Log API keys or secrets (SDK redacts these automatically)
- Commit
.envfiles (use.env.exampleas template) - Pass credentials in URLs or query strings
- Store credentials in code or version control
DO:
- Use environment variables for credentials
- Use
.envfiles locally (gitignored) - Use secret managers in production (AWS Secrets Manager, Vault, etc.)
// β
GOOD: Load from environment
let api_key = var.ok;
let api_secret = var.ok;
// β BAD: Hardcoded credentials
let api_key = Some; // NEVER DO THIS
What the SDK Logs
| Data | Logged? | Notes |
|---|---|---|
| API Key | β Never | Redacted to *** |
| API Secret | β Never | Never appears in logs |
| Auth tokens | β Never | Generated internally, not logged |
| Symbols/pairs | β Yes | e.g., "BTC/USD" |
| Prices/volumes | β Yes | Market data is public |
| Connection state | β Yes | "Connected", "Reconnecting" |
| Error messages | β Yes | Without sensitive data |
Network Security
- All connections use TLS 1.2+ (wss://)
- Certificate validation is enabled by default
- No plaintext WebSocket (ws://) in production
Reporting Vulnerabilities
If you discover a security vulnerability, please:
- Do not open a public issue
- Email security concerns to the maintainers
- Allow 90 days for a fix before public disclosure
Versioning & Compatibility
This SDK follows Semantic Versioning with a strong compatibility promise:
Post-1.0 Guarantee:
- No breaking changes in
preludemodule without major version bump - Config additions are non-breaking (new fields have defaults)
- New enum variants are non-breaking (
#[non_exhaustive]) - MSRV bumps require major version
Pre-1.0 (current):
- Minor versions may include breaking changes (documented with
BREAKING:) - Patch versions are always safe to upgrade
See CHANGELOG.md for detailed upgrade notes.
Disclaimer
This SDK is not officially affiliated with Kraken. Use at your own risk in production environments.
Support
For questions and support:
- Check the examples directory
- Review the API documentation:
cargo doc --open - Open an issue on GitHub
- See CHANGELOG.md for version history
Built with β€οΈ in Rust