Kraky 🐙
A lightweight, high-performance Rust SDK for connecting to the Kraken Exchange WebSocket API v2.
🏆 For Hackathon Judges
Quick test in under 2 minutes:
Prerequisites
- Rust 1.70+ installed (install here)
Run the Demo
# Clone the repo
# Run all tests (29 tests)
# ⭐ RECOMMENDED: Run the comprehensive demo (shows all features)
# Basic examples (single data type):
# Multi-subscription examples:
# Advanced examples:
# Authentication examples (requires API credentials):
# Trading examples:
What You'll See
Demo Example Output (abbreviated):
╔══════════════════════════════════════════════════════════════╗
║ 🐙 KRAKY SDK DEMO - Kraken Forge Hackathon ║
╚══════════════════════════════════════════════════════════════╝
═══════════════════════════════════════════════════════════════
FEATURE 1: WebSocket Connection
═══════════════════════════════════════════════════════════════
📡 Connecting to Kraken WebSocket API...
✅ Connected!
═══════════════════════════════════════════════════════════════
FEATURE 2: Connection Events
═══════════════════════════════════════════════════════════════
📌 Subscribed to connection events
Events: Connected, Disconnected, Reconnecting, Reconnected...
═══════════════════════════════════════════════════════════════
FEATURE 3: Connection State
═══════════════════════════════════════════════════════════════
Current state: ✅ Connected
is_connected(): true
Reconnect Config: enabled, 500ms initial, 30s max, 2.0x backoff
═══════════════════════════════════════════════════════════════
FEATURE 5: Live Market Data (15 seconds)
═══════════════════════════════════════════════════════════════
📖 ORDERBOOK UPDATE #1
Best Bid: $97234.50 | Best Ask: $97235.00
Spread: $0.50 | Mid: $97234.75
🟢 TRADE: Buy 0.050000 BTC @ $97235.00
📈 TICKER: $97235.00 (24h: +2.35%) Vol: 1234.56 BTC
═══════════════════════════════════════════════════════════════
FEATURE 6: Backpressure Monitoring
═══════════════════════════════════════════════════════════════
Backpressure stats (delivered / dropped / drop rate):
📖 Orderbook: 47 / 0 / 0.00%
💱 Trades: 23 / 0 / 0.00%
═══════════════════════════════════════════════════════════════
FEATURE 7: Orderbook Checksum Validation (CRC32)
═══════════════════════════════════════════════════════════════
Calculated Checksum: 0x1A2B3C4D
Checksum Valid: ✅ Yes
═══════════════════════════════════════════════════════════════
FEATURE 8: Orderbook Imbalance Detection
═══════════════════════════════════════════════════════════════
┌─────────────────────────────────────┐
│ Bid Volume: 12.3456 BTC │
│ Ask Volume: 8.7654 BTC │
│ Imbalance: +17.02% │
│ Signal: 🟢 BULLISH │
└─────────────────────────────────────┘
╔══════════════════════════════════════════════════════════════╗
║ 🎉 DEMO COMPLETE! ║
╠══════════════════════════════════════════════════════════════╣
║ Features Demonstrated: ║
║ ✅ WebSocket Connection ║
║ ✅ Connection Events (lifecycle callbacks) ║
║ ✅ Connection State Monitoring ║
║ ✅ Multiple Subscriptions ║
║ ✅ Backpressure Monitoring ║
║ ✅ Orderbook Checksum Validation ║
║ ✅ Orderbook Imbalance Detection ║
║ ✅ Managed Orderbook State ║
╚══════════════════════════════════════════════════════════════╝
Key Features Demonstrated in Demo
| Feature # | What It Shows |
|---|---|
| 1 | WebSocket Connection |
| 2 | Connection Events (lifecycle callbacks) |
| 3 | Connection State Monitoring |
| 4 | Multiple Subscriptions (orderbook, trades, ticker) |
| 5 | Real-time Market Data Processing |
| 6 | Backpressure Monitoring |
| 7 | Orderbook Checksum Validation (CRC32) |
| 8 | Orderbook Imbalance Detection |
| 9 | Managed Orderbook State |
Examples Quick Reference
| Example | Required Features | What It Shows |
|---|---|---|
orderbook |
(default) | Real-time depth, managed state, spread calculation |
trades |
trades |
Live trade stream, buy/sell sides |
ticker |
ticker |
Price, volume, 24h change |
ohlc |
ohlc |
Candlestick data for charting |
multi_subscribe |
trades,ticker |
Concurrent subscriptions with tokio::select! |
benchmark |
orderbook,trades |
Performance testing |
telegram_imbalance_bot |
telegram-alerts |
🤖 Real-time Telegram alerts with imbalance signals |
auth_example |
private |
🔐 HMAC-SHA256 authentication for private channels |
telegram_private_alerts |
telegram,private |
📱 Private account alerts (balances, orders, executions) |
whale_watcher |
telegram-alerts |
🐋 Large order detection with Telegram notifications |
multi_pair_monitor |
market-data,analytics |
📊 Monitor multiple trading pairs simultaneously |
liquidity_monitor |
analytics |
💧 Track market liquidity and spread changes |
simple_price_alerts |
telegram-alerts |
🔔 Beginner-friendly price threshold alerts |
export_to_csv |
trades,analytics |
📊 Export live market data to CSV for analysis |
telegram_trading_demo |
telegram,trading |
🎯 Trading demo - NO credentials needed! Shows all notifications |
telegram_trading_bot |
telegram,trading |
💰 Complete trading bot with order management (needs API keys) |
demo |
full |
⭐ Comprehensive showcase of all features |
Features
- Real-time Market Data: Stream orderbook, trades, tickers, and OHLC candles
- Managed Orderbook State: Automatic reconstruction from incremental updates
- Orderbook Imbalance Detection: Built-in bullish/bearish signal generation
- Orderbook Checksum Validation: CRC32 validation to detect data corruption
- 🔐 Authenticated WebSocket: HMAC-SHA256 authentication for private channels (optional)
- Private Account Data: Real-time balance, order, and execution updates (optional)
- 💰 Trading via WebSocket: Place, cancel, and manage orders - no REST API needed (optional)
- 🤖 Telegram Bot Integration: Real-time alerts with imbalance signals (optional)
- Smart Reconnection: Automatic reconnection with exponential backoff
- Connection Events: Subscribe to connect/disconnect/reconnect lifecycle events
- Type-safe API: Strongly typed models for all Kraken message types
- Async/Await: Built on Tokio for efficient async I/O
- Zero-copy Parsing: Efficient JSON deserialization with Serde
- Backpressure Control: Bounded channels prevent memory issues
- Kraken Error Parsing: Structured parsing of Kraken API errors
- Automatic Heartbeat: Built-in ping/pong handling
Installation
Add to your Cargo.toml:
[]
= { = "https://github.com/SarpTekin/kraky" }
= { = "1.35", = ["full"] }
🎛️ Feature Flags - Choose What You Need
Kraky uses feature flags to keep your binary lightweight. Only compile what you actually use!
🧭 Quick Decision Guide
┌─────────────────────────────────────────────────────────────────┐
│ What do you want to do? │
└─────────────────────────────────────────────────────────────────┘
│
┌─────────────────────┼─────────────────────┐
▼ ▼ ▼
📊 Market Data 🔐 Private Data 💰 Trading
│ │ │
├─ orderbook ✓ ├─ private ├─ trading
├─ trades │ (adds auth) │ (adds auth + private)
├─ ticker │ │
└─ ohlc └─ 📱 + telegram └─ 📱 + telegram
(notifications) (trade alerts)
📈 Analytics? 🤖 Telegram Alerts? ⚡ Performance?
│ │ │
├─ analytics ├─ telegram-alerts ├─ simd
└─ checksum │ (auto-includes └─ (2-3x faster JSON)
│ telegram,
│ analytics,
│ ticker)
📦 Default Features (Always Included)
When you add Kraky with no feature flags, you get:
= { = "https://github.com/SarpTekin/kraky" }
Includes:
- ✅
reconnect- Smart reconnection with exponential backoff - ✅
events- Connection lifecycle event callbacks - ✅
orderbook- Orderbook depth subscription and managed state
Binary size: ~7.2 MB Dependencies added: 0 (core only)
📊 Data Type Features (Opt-in)
Choose which market data types you need:
| Feature | What You Get | Added Size | Dependencies |
|---|---|---|---|
trades |
Real-time trade execution stream | +50 KB | 0 |
ticker |
Price, volume, 24h stats | +45 KB | 0 |
ohlc |
Candlestick/OHLC data | +40 KB | 0 |
orderbook |
Depth updates (included by default) | ✓ | 0 |
Meta feature: market-data = all of the above
# Just trades
= { = "...", = ["trades"] }
# All market data types
= { = "...", = ["market-data"] }
🎯 Analytics Features (Opt-in)
Advanced orderbook analysis:
| Feature | What You Get | Added Size | Requires |
|---|---|---|---|
analytics |
Imbalance detection, signals | +25 KB | orderbook |
checksum |
CRC32 orderbook validation | +15 KB | orderbook |
Dependencies added:
analytics: 0 additional depschecksum: +1 dep (crc32fast)
# Orderbook with analytics
= { = "...", = ["analytics"] }
# With checksum validation too
= { = "...", = ["analytics", "checksum"] }
🔐 Authentication & Private Data
Access your account data and trade via WebSocket:
┌──────────────────────────────────────────────────────┐
│ Feature Dependency Chain │
├──────────────────────────────────────────────────────┤
│ │
│ auth ──> private ──> trading │
│ │ │ │ │
│ │ │ └─> Place/cancel orders │
│ │ └──> Balances, orders, executions │
│ └────> HMAC-SHA256 signing │
│ │
└──────────────────────────────────────────────────────┘
| Feature | What You Get | Added Size | Dependencies |
|---|---|---|---|
auth |
HMAC-SHA256 authentication | +50 KB | +3 (hmac, sha2, base64) |
private |
Balance/order/execution updates | +0 KB | Includes auth |
trading |
Place/cancel/amend orders | +3 KB | Includes auth + private |
Example usage:
# Private account data
= { = "...", = ["private"] }
# Automatically includes: auth
# Full trading capabilities
= { = "...", = ["trading"] }
# Automatically includes: auth + private
📱 Telegram Integration
Real-time notifications via Telegram bot:
| Feature | What You Get | Added Size | Requires |
|---|---|---|---|
telegram |
Basic Telegram notifications | +800 KB | None |
telegram-alerts |
Smart alerts with imbalance signals | +800 KB | telegram + analytics + ticker |
Dependencies added: +1 (teloxide)
# Basic Telegram notifications
= { = "...", = ["telegram"] }
# Smart alerts with orderbook signals
= { = "...", = ["telegram-alerts"] }
# Auto-includes: telegram, analytics, ticker
# Telegram + Private account alerts
= { = "...", = ["telegram", "private"] }
# Telegram + Trading alerts
= { = "...", = ["telegram", "trading"] }
⚡ Performance Features
Boost JSON parsing speed:
| Feature | What You Get | Added Size | Trade-offs |
|---|---|---|---|
simd |
SIMD-accelerated JSON (2-3x faster) | +100 KB | +15 dependencies |
When to use: High-frequency trading, processing thousands of updates/sec
= { = "...", = ["full", "simd"] }
🎁 Meta Features (Convenience)
Bundles of commonly used features:
| Meta Feature | Includes | Use Case |
|---|---|---|
market-data |
orderbook + trades + ticker + ohlc |
Comprehensive market monitoring |
full |
All features except simd |
Everything you need |
# Everything (trading, analytics, telegram, private)
= { = "...", = ["full"] }
🎯 Common Combinations
Choose your use case:
| I want to... | Features to enable | Why? |
|---|---|---|
| 🎯 Track orderbook | ["orderbook"] (default) |
Core features, no extras |
| 📈 Detect imbalances | ["analytics"] |
Adds signal generation |
| 🤖 Build alert bot | ["telegram-alerts"] |
Telegram + analytics + ticker |
| 🔐 Monitor my account | ["telegram", "private"] |
Balance/order alerts |
| 💰 Build trading bot | ["trading", "analytics"] |
Trade + signals |
| 📱 Trading with alerts | ["telegram", "trading"] |
Full trading notifications |
| 🐋 Watch for whales | ["telegram-alerts"] |
Large order detection |
| ⚡ High-frequency trading | ["trading", "simd"] |
Fast execution |
| 📊 Multi-asset dashboard | ["market-data", "analytics"] |
All data + analytics |
| 🎓 Learning/testing | ["orderbook"] (default) |
Start simple |
📏 Binary Size Impact
Stay lightweight - only pay for what you use:
┌────────────────────────────────────────────────────┐
│ Configuration Size vs Full Added │
├────────────────────────────────────────────────────┤
│ full (everything) 8.5 MB baseline — │
│ market-data only 7.8 MB -8% — │
│ orderbook + trading 7.25 MB -15% +53KB │
│ orderbook + private 7.23 MB -15% +50KB │
│ orderbook (default) 7.2 MB -15% — │
│ trades only 6.9 MB -19% — │
└────────────────────────────────────────────────────┘
Key takeaway:
- 🪶 Authentication adds only ~50 KB (0.6%)
- 🪶 Trading adds only ~3 KB on top of auth (0.04%)
- 🪶 The SDK remains lightweight even with full capabilities!
🔍 Dependency Count by Feature
Understanding what each feature pulls in:
Core (no features) 12 deps
├─ tokio, serde, serde_json, futures-util
├─ native-tls, tokio-tungstenite
└─ thiserror, tracing, url, chrono, uuid, parking_lot
+ auth +3 deps (hmac, sha2, base64)
+ checksum +1 dep (crc32fast)
+ simd +15 deps (simd-json + dependencies)
+ telegram +1 dep (teloxide - brings ~20 transitive)
Data types (trades/ticker/ohlc) +0 deps (just code)
Analytics +0 deps (just code)
Total with full feature: ~30-35 dependencies
Total with telegram + full: ~50-55 dependencies
Total minimal (trades only): 12 dependencies
💡 Disabling Default Features
Want maximum control? Disable defaults and choose exactly what you need:
# Minimal - only trades, no reconnection or events
= {
git = "https://github.com/SarpTekin/kraky",
= false,
= ["trades"]
}
# Custom combination - orderbook + reconnect only
= {
git = "https://github.com/SarpTekin/kraky",
= false,
= ["orderbook", "reconnect"]
}
Note: Most users should keep the default features enabled for reliability.
Quick Start
use KrakyClient;
async
Subscription Types
Orderbook
Subscribe to real-time orderbook depth updates. The SDK maintains a local orderbook state that is automatically updated.
// Subscribe with depth of 10, 25, 100, 500, or 1000 levels
let mut subscription = client.subscribe_orderbook.await?;
while let Some = subscription.next.await
Trades
Subscribe to real-time trade executions.
let mut trades = client.subscribe_trades.await?;
while let Some = trades.next.await
Ticker
Subscribe to ticker updates with price and volume information.
let mut ticker = client.subscribe_ticker.await?;
while let Some = ticker.next.await
OHLC (Candlesticks)
Subscribe to OHLC candle updates for technical analysis.
use Interval;
// Available intervals: Min1, Min5, Min15, Min30, Hour1, Hour4, Day1, Week1, Day15
let mut ohlc = client.subscribe_ohlc.await?;
while let Some = ohlc.next.await
Multiple Subscriptions
Subscribe to multiple streams and process them concurrently:
let mut btc_trades = client.subscribe_trades.await?;
let mut eth_trades = client.subscribe_trades.await?;
let mut btc_ticker = client.subscribe_ticker.await?;
loop
Authentication & Private Channels
Access private WebSocket channels for account data using HMAC-SHA256 authentication:
Setup Credentials
use ;
// Load credentials from environment variables
let api_key = var?;
let api_secret = var?;
let credentials = new;
// Generate authentication token
let nonce = now
.duration_since?
.as_millis as u64;
let token = credentials.generate_token?;
Private Data Types
Balance Updates
Monitor account balance changes in real-time:
Order Updates
Track order lifecycle (placed, filled, cancelled):
Execution Updates
Receive trade execution notifications:
Example: Private Channels with Telegram
See examples/telegram_private_alerts.rs for a complete bot that sends Telegram notifications for:
- Balance changes
- Order status updates
- Trade executions
- Portfolio summaries
Trading via WebSocket
NEW: Place, cancel, and manage orders directly via WebSocket - no REST API needed!
The SDK provides full trading capabilities while remaining lightweight (~3KB added).
🎯 Try the Demo (No Account Needed!)
Before diving into the code, see all trading features in action:
# Run the complete trading demo - NO Kraken credentials needed!
This demo showcases:
- ✅ All 7 types of trading notifications
- ✅ Order lifecycle (place → amend → cancel → fill)
- ✅ Real-time Telegram alerts
- ✅ Complete trading workflow simulation
- ✅ Perfect for hackathon presentations!
Quick Start
use ;
async
Order Types Supported
All via WebSocket API v2:
| Order Type | Description |
|---|---|
Market |
Execute immediately at best price |
Limit |
Execute at specified price or better |
StopLoss |
Market order triggered at stop price |
StopLossLimit |
Limit order triggered at stop price |
TakeProfit |
Market order at profit target |
TakeProfitLimit |
Limit order at profit target |
TrailingStop |
Stop that follows price movement |
TrailingStopLimit |
Trailing stop with limit price |
Iceberg |
Hidden volume order |
Trading Methods
Place Orders
// Market orders
let buy = market_buy;
let sell = market_sell;
// Limit orders
let buy = limit_buy;
let sell = limit_sell
Cancel Orders
// Cancel single order
client.cancel_order.await?;
// Cancel all orders
let response = client.cancel_all_orders.await?;
println!;
Amend Orders
use AmendOrderParams;
let amend = AmendOrderParams ;
client.amend_order.await?;
Validation Mode (Safe Testing)
Test orders without executing them:
let order = market_buy
.with_validate; // Order will be validated but NOT executed
let response = client.place_order.await?;
// Returns validation result without placing real order
Perfect for:
- Testing your bot logic
- Hackathon demonstrations
- Development without risk
Telegram Trading Notifications
Get instant alerts for all trading events:
use TelegramNotifier;
let bot = new;
// Order placed
bot.send_order_placed.await?;
// Order filled
bot.send_order_filled.await?;
// Order cancelled
bot.send_order_cancelled.await?;
// Order failed
bot.send_order_failed.await?;
// Daily summary
bot.send_trading_summary.await?;
Complete Trading Examples
We provide 2 examples to help you get started:
1. Trading Demo (No Credentials Needed!) 🎯
Perfect for learning and hackathon presentations:
Features:
- ✅ Demonstrates all 7 notification types
- ✅ Shows complete trading workflow
- ✅ No Kraken API credentials required
- ✅ Perfect for presentations and demos
2. Real Trading Bot (Requires API Keys) 💰
See examples/telegram_trading_bot.rs for a full implementation featuring:
- Market and limit order placement
- Order cancellation and amendment
- Real-time Telegram notifications
- Error handling
- Validation mode (safe testing)
# Set your API credentials
# Run in validation mode (safe - no real trades)
# Enable real trading (use with caution!)
ENABLE_REAL_TRADING=true
API Reference (Trading)
| Method | Description |
|---|---|
place_order(creds, params) |
Place a new order |
cancel_order(creds, order_id) |
Cancel an order |
cancel_all_orders(creds) |
Cancel all open orders |
amend_order(creds, params) |
Modify an existing order |
All trading operations use WebSocket API v2 - no REST calls needed!
Error Handling
Kraken Error Parsing
The SDK parses Kraken's error format (SeverityCategory:Message) into structured types:
use ;
// Kraken returns errors like "EQuery:Unknown asset pair"
// The SDK parses these into structured errors:
match result
Connection Errors
use ;
match connect.await
Data Types
Orderbook
Trade
Ticker
OHLC
Orderbook Imbalance Detection
The SDK provides built-in orderbook imbalance calculations for detecting buy/sell pressure:
if let Some = client.get_orderbook
Imbalance Metrics
| Method | Description |
|---|---|
imbalance() |
Full orderbook imbalance (-1.0 to 1.0) |
imbalance_top_n(n) |
Imbalance of top N levels only |
imbalance_within_depth(pct) |
Imbalance within % of mid price |
imbalance_metrics() |
Detailed metrics (volumes, ratio, signal) |
🤖 Telegram Bot Integration
Get real-time market alerts delivered to Telegram using Kraky's advanced orderbook analytics. This feature showcases a practical, real-world application of the SDK's imbalance detection capabilities.
Features
- 📊 Price Alerts - Get notified when price crosses thresholds
- 🎯 Imbalance Signals - Bullish/Bearish/Neutral signals based on orderbook depth
- 📈 Orderbook Summaries - Best bid/ask, spread, mid-price updates
- 🔔 Connection Events - Monitor WebSocket connection status
- ⚡ Real-time Delivery - Instant notifications via Telegram
Installation
The Telegram integration is optional and adds approximately 800KB to your binary size.
# Enable Telegram alerts with imbalance detection
= { = "https://github.com/SarpTekin/kraky", = ["telegram-alerts"] }
# Or just basic Telegram notifications
= { = "https://github.com/SarpTekin/kraky", = ["telegram"] }
Note: Remains lightweight - users who don't enable this feature add 0 bytes to their binary.
Quick Start
use ;
async
Setup Instructions
-
Create a Telegram Bot
- Message @BotFather on Telegram
- Send
/newbotand follow the instructions - Save your bot token
-
Get Your Chat ID
- Message @userinfobot
- It will reply with your chat ID
-
Set Environment Variables
-
Run the Example
Alert Types
Imbalance Alerts (Leverages Kraky's Unique Analytics)
The most powerful feature - get notified of orderbook pressure changes:
let metrics = ob.imbalance_metrics;
let signal = metrics.signal; // 15% imbalance threshold
bot.send_imbalance_alert.await?;
Example Telegram Message:
🟢 BTC/USD Orderbook Imbalance Alert
📊 Signal: BULLISH
──────────────────────────────
📈 Metrics:
• Bid Volume: 12.3456 BTC
• Ask Volume: 8.7654 BTC
• Bid/Ask Ratio: 1.41
• Imbalance: +17.02%
💡 Interpretation:
Strong buy pressure detected - more bids than asks
Price Threshold Alerts
bot.send_threshold_alert.await?;
Example Message:
📈 BTC/USD Threshold Alert
Current Price: $100,500.00
Threshold: $100,000.00
Status: Price is above threshold
Change: 0.50%
Orderbook Summary
bot.send_orderbook_summary.await?;
Connection Status
bot.send_connection_status.await?;
Example: Complete Trading Bot
See examples/telegram_imbalance_bot.rs for a complete implementation featuring:
- Real-time imbalance monitoring
- Price threshold alerts
- Connection event notifications
- Hourly summary reports
- Configurable alert thresholds
Why This Matters
This Telegram integration demonstrates:
- Practical Application - Real-world use case for market data
- Modular Design - Optional feature that doesn't bloat the core SDK
- Advanced Analytics - Leverages Kraky's superior imbalance detection
- User-Friendly - Easy setup with environment variables
- Production-Ready - Async, error handling, connection monitoring
API Reference
Public Market Data Notifications
| Method | Description |
|---|---|
send_alert(message) |
Send basic text alert |
send_imbalance_alert(symbol, metrics, signal) |
Send imbalance signal with full metrics |
send_price_alert(symbol, price, context) |
Send formatted price alert |
send_threshold_alert(symbol, price, threshold, above) |
Send threshold crossing alert |
send_orderbook_summary(symbol, bid, ask, spread, mid) |
Send orderbook snapshot |
send_connection_status(connected, details) |
Send connection status update |
send_whale_alert(symbol, side, price, volume) |
Send large order detection alert |
send_spread_alert(symbol, spread_bps, avg_spread, ratio) |
Send wide spread warning |
send_divergence_alert(symbol, price1, price2, pct_diff) |
Send price divergence alert |
send_trade_alert(symbol, side, price, volume) |
Send significant trade alert |
Private Account Notifications (requires private feature)
| Method | Description |
|---|---|
send_balance_update(update) |
Send account balance change notification |
send_order_update(update) |
Send order status update (placed, filled, cancelled) |
send_execution_alert(update) |
Send trade execution notification |
send_portfolio_summary(update) |
Send portfolio summary with total value |
Trading Notifications (requires trading feature)
| Method | Description |
|---|---|
send_order_placed(response, params) |
Send order placement confirmation |
send_order_filled(symbol, side, qty, price, id) |
Send order fill notification |
send_order_cancelled(symbol, order_id, reason) |
Send order cancellation alert |
send_order_failed(params, error) |
Send order failure notification |
send_order_amended(response, params) |
Send order modification confirmation |
send_trading_summary(trades, volume, pl, win_rate) |
Send daily trading summary |
Orderbook Checksum Validation
Kraken sends CRC32 checksums with orderbook updates. The SDK validates these automatically:
if let Some = client.get_orderbook
// Validate all orderbooks and auto-reconnect if corrupted
let corrupted_count = client.validate_orderbooks_and_reconnect?;
// Quick check for specific pair
if client.is_orderbook_valid == Some
Checksum Methods
| Method | Description |
|---|---|
calculate_checksum() |
Calculate CRC32 of top 10 levels |
validate_checksum(expected) |
Returns true if checksum matches |
checksum_validation(expected) |
Returns detailed ChecksumValidation struct |
Smart Reconnection
The SDK automatically reconnects when the connection drops, with configurable exponential backoff:
use ;
// Default: automatic reconnection with exponential backoff
let client = connect.await?;
// Aggressive reconnection (for low-latency needs)
let client = connect_with_reconnect.await?;
// Conservative reconnection (to avoid rate limiting)
let client = connect_with_reconnect.await?;
// Disable reconnection
let client = connect_with_reconnect.await?;
// Custom configuration
let config = ReconnectConfig ;
let client = connect_with_reconnect.await?;
Connection State
Monitor connection state programmatically:
use ConnectionState;
// Check connection status
if client.is_connected
if client.is_reconnecting
// Get detailed state
match client.connection_state
// Manually trigger reconnection
client.reconnect?;
Reconnect Presets
| Preset | Initial Delay | Max Delay | Backoff | Max Attempts |
|---|---|---|---|---|
default() |
500ms | 30s | 2.0x | Unlimited |
aggressive() |
100ms | 5s | 1.5x | Unlimited |
conservative() |
1s | 60s | 2.0x | 10 |
disabled() |
- | - | - | 0 |
Connection Events
Subscribe to connection lifecycle events for monitoring and logging:
use ConnectionEvent;
let mut events = client.subscribe_events;
spawn;
| Event | Description |
|---|---|
Connected |
Initial connection successful |
Disconnected(reason) |
Connection lost |
Reconnecting(attempt) |
Starting reconnection attempt |
Reconnected |
Reconnection successful |
ReconnectFailed(attempt, error) |
Reconnection attempt failed |
ReconnectExhausted |
Max attempts reached, giving up |
Backpressure Monitoring
Subscriptions use bounded channels (default: 1000 messages). If your consumer is too slow, older messages are dropped to keep the latest data:
let mut trades = client.subscribe_trades.await?;
// Process messages...
while let Some = trades.next.await
// Check stats
let stats = trades.stats;
println!;
Supported Trading Pairs
The SDK supports all trading pairs available on Kraken. Common pairs include:
BTC/USD,BTC/EUR,BTC/USDTETH/USD,ETH/EUR,ETH/BTCXRP/USD,SOL/USD,DOT/USDDOGE/USD,ADA/USD,AVAX/USD
See Kraken's asset pairs for the full list.
Performance
The SDK is designed for low-latency market data processing:
| Feature | Benefit |
|---|---|
| Async I/O (Tokio) | Non-blocking network operations |
| Zero-copy parsing | Efficient memory usage |
| Managed state | Pre-computed orderbook metrics |
| Bounded channels | Backpressure prevents memory issues |
| Structured errors | Fast error categorization |
Test Coverage
29 tests covering:
- Orderbook operations (17 tests) - including imbalance & checksum validation
- Subscription handling (4 tests)
- Error parsing (6 tests)
- Reconnection logic (2 tests)
License
This project is licensed under the MIT License - see the LICENSE file for details.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Disclaimer
This SDK is provided for educational and informational purposes. Trading cryptocurrencies involves risk. Use at your own discretion.
Built for the Kraken Forge Hackathon 🐙