kalshi-rust
A comprehensive async Rust wrapper for the Kalshi trading API, providing both HTTPS and WebSocket support for building high-performance trading bots on the Kalshi prediction markets platform.
Features
- Async/Await: Built on
tokiofor high-performance concurrent operations - Complete API Coverage: Full support for Kalshi API v2 endpoints
- WebSocket Support: Real-time market data and order updates
- Type Safety: Strongly typed API with comprehensive error handling
- RSA-PSS Authentication: Secure key-based authentication
- Demo & Production: Support for both paper trading (demo) and live trading environments
- Batch Operations: Efficient batch order creation and cancellation
- Comprehensive Examples: Well-documented examples for common use cases
Installation
Add kalshi to your Cargo.toml:
[]
= "0.9"
= { = "1", = ["full"] }
Quick Start
Getting API Credentials
- Sign up for an account at demo.kalshi.com (for testing) or kalshi.com (for production)
- Navigate to your account settings and generate an API key
- Download the private key file (
.pemformat) - Save the key ID (UUID format) shown in the UI
Basic Example
use ;
async
Authentication
kalshi-rust uses RSA-PSS key-based authentication for secure API access. Authentication is handled automatically when creating a Kalshi instance.
Demo vs Production Environments
// Demo mode (paper trading - recommended for testing)
let kalshi_demo = new.await?;
// Production mode (real money trading)
let kalshi_prod = new.await?;
Credential Management
Store your credentials securely using environment variables:
use env;
let key_id = var?;
let pem_path = var?;
let kalshi = new.await?;
Core Features
Trading Operations
Create Orders
use ;
// Create a limit order to buy 10 "Yes" contracts at 55 cents
let order = kalshi.create_order.await?;
println!;
Batch Order Creation
use OrderCreationField;
let orders = vec!;
let results = kalshi.batch_create_order.await?;
for in results.iter.enumerate
Amend Orders
use ;
// Change the price of an existing order
let response = kalshi.amend_order.await?;
println!;
println!;
Cancel Orders
// Cancel a single order
let = kalshi.cancel_order.await?;
println!;
// Batch cancel orders
let order_ids = vec!;
let results = kalshi.batch_cancel_order.await?;
Get Portfolio Information
// Get account balance
let balance = kalshi.get_balance.await?;
println!;
// Get positions
let = kalshi.get_positions.await?;
for position in market_positions
// Get fills
let = kalshi.get_fills.await?;
// Get settlements
let = kalshi.get_settlements.await?;
Market Data
Get Markets
// Get all open markets
let = kalshi.get_markets.await?;
for market in markets
// Get a specific market
let market = kalshi.get_market.await?;
println!;
Get Orderbook
// Get orderbook with depth limit
let orderbook = kalshi.get_orderbook.await?;
// Best bid/ask in cents
if let Some = orderbook.yes
// Dollar prices (as tuples of (f32, i32))
for in &orderbook.yes_dollars
Get Candlestick Data
use Utc;
let now = now.timestamp;
let one_day_ago = now - 86400;
// Single market candlesticks
let candlesticks = kalshi.get_market_candlesticks.await?;
for candle in candlesticks
// Batch candlestick retrieval for multiple markets
let tickers = vec!;
let batch_data = kalshi.batch_get_market_candlesticks.await?;
for market_data in batch_data
Get Trades
// Get recent trades for a market
let = kalshi.get_trades.await?;
for trade in trades
Get Series and Events
// Get series
let = kalshi.get_series_list.await?;
// Get specific series
let series = kalshi.get_series.await?;
// Get events
let = kalshi.get_multiple_events.await?;
WebSocket Real-Time Data
Connect to the WebSocket API for real-time market data and trading updates.
use Channel;
use StreamExt;
// Create WebSocket client from existing Kalshi instance
let mut ws = kalshi.websocket;
// Connect to WebSocket
ws.connect.await?;
// Subscribe to orderbook updates for a market
let sub = ws.subscribe.await?;
println!;
// Listen for messages
while let Some = ws.next_message.await
// Unsubscribe and disconnect
ws.unsubscribe.await?;
ws.disconnect.await?;
Available WebSocket Channels
use Channel;
// Market-specific channels
let orderbook_channel = Orderbook ;
let ticker_channel = Ticker ;
let trade_channel = Trade ;
// Portfolio channels
let fill_channel = Fill;
let order_channel = OrderUpdate;
// Subscribe to a channel
let subscription = ws.subscribe.await?;
Exchange Information
// Get exchange status
let status = kalshi.get_exchange_status.await?;
println!;
println!;
// Get exchange schedule
let schedule = kalshi.get_exchange_schedule.await?;
println!;
Error Handling
kalshi-rust provides comprehensive error handling through the KalshiError enum:
use KalshiError;
match kalshi.create_order.await
Error Types
RequestError: HTTP/network errors, serialization failures, client/server errorsUserInputError: Invalid parameters or input validation failuresAuth: Authentication and authorization errorsInternalError: Unexpected internal errors (please report these!)
API Reference
Core Modules
| Module | Description |
|---|---|
portfolio |
Orders, positions, fills, settlements, balance management |
market |
Markets, orderbooks, trades, series, candlesticks |
events |
Event data and multi-event queries |
exchange |
Exchange status and trading schedule |
websocket |
Real-time WebSocket data streaming |
api_keys |
API key management |
collection |
Collection-related endpoints |
search |
Search functionality |
live_data |
Live milestone data feeds |
Key Enums
// Trading environment
// Order parameters
// Advanced order parameters
For complete API documentation, run:
Or visit the online documentation.
Testing
The library includes comprehensive tests. To run them:
For authenticated tests, set up environment variables:
See TESTING.md for detailed testing instructions.
Examples
Complete examples are available in the sample_bot directory.
Example: Simple Market Scanner
use ;
async
Contributing
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes with tests
- Run
cargo fmtandcargo clippy - Submit a pull request
Code Style
This project follows standard Rust conventions:
- Run
cargo fmtbefore committing - Ensure
cargo clippypasses with no warnings - Add tests for new functionality
- Document public APIs with doc comments
Resources
- GitHub Repository: dpeachpeach/kalshi-rust
- Crates.io: kalshi
- Documentation: docs.rs/kalshi
- Kalshi API Documentation: Kalshi API Docs
- Kalshi Platform: kalshi.com
- Kalshi Demo: demo.kalshi.com
License
This project is dual-licensed under:
- MIT License (LICENSE-MIT or http://opensource.org/licenses/MIT)
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
You may choose either license for your use.
Disclaimer
This library is not officially affiliated with Kalshi. Use at your own risk. Trading involves financial risk. Always test with demo mode before trading with real money.
Support
- Issues: GitHub Issues
- Discussions: GitHub Discussions
Acknowledgments
Developed by the Rust trading community. Special thanks to all contributors who have helped improve this library.
If you find this library useful, please consider giving it a star on GitHub!