Crate kalshi_rust

Crate kalshi_rust 

Source
Expand description

An HTTPS and Websocket wrapper that allows users to write trading bots for the Kalshi events trading platform.

kalshi-rust is asynchronous, performant, and succint. Dash past verbose and annoying HTTPS requests and use this wrapper to quickly write blazingly fast trading bots in Rust!

As of version 0.9.0, HTTPS features are fully complete but websocket support and advanced API access features are not complete. If you’d like to keep up on kalshi-rust’s development, report bugs, or view a sample trading script, feel free to visit the github! A star would also be greatly appreciated, I’m a student developer writing this for free and any recognition is incredibly helpful!

§The Kalshi Struct

The Kalshi struct is the central component of this crate. All authentication, order routing, market requests, and position snapshots are handled through the struct and its methods.

For more details, see Kalshi.

For a quick tutorial / beginners guide, jump here.

§Initializing the Kalshi struct in demo mode.

use kalshi::Kalshi;
use kalshi::TradingEnvironment;

let kalshi_instance = Kalshi::new(TradingEnvironment::DemoMode, "your-key-id", "path/to/private.pem").await?;

§Quick Start Guide

First, list the Kalshi struct as a dependency in your crate.

kalshi = { version = "0.9"}

Initialize the Kalshi Struct with key-based authentication:

  • IMPORTANT: The authentication is handled automatically when creating a new instance.
  • Store your key ID and private key file securely, an implementation of extracting these from local environmental variables is available here
use kalshi::Kalshi;
use kalshi::TradingEnvironment;

let key_id = "your-key-id";
let pem_path = "path/to/private.pem";

let kalshi_instance = Kalshi::new(TradingEnvironment::DemoMode, key_id, pem_path).await?;

After logging in, you can call any method present in the crate without issue. Here is a script that buys a ‘yes’ contract on November 13th’s New York temperature market.

let new_york_ticker = "HIGHNY-23NOV13-T51".to_string();

let bought_order = kalshi_instance
    .create_order(
    kalshi::Action::Buy,
    None,
    1,
    kalshi::Side::Yes,
    new_york_ticker,
    kalshi::OrderType::Limit,
    None,
    None,
    None,
    None,
    Some(5)).await.unwrap();

Refer to the rest of the documentation for details on all other methods!

§Returned Values

Whenever a user makes a method call using the kalshi struct, data is typically returned in structs that encapsulate the json fields returned by the server. All data in the structs is owned so a user can access the attributes without issue.

§Examples:

§Obtaining the Exchange’s current status

Returns a struct that represents whether trading or the exchange are currently active.

use kalshi::Kalshi;
use kalshi::TradingEnvironment;
let kalshi_instance = Kalshi::new(TradingEnvironment::DemoMode, "your-key-id", "path/to/private.pem").await?;

kalshi_instance.get_exchange_status().await.unwrap();
§Obtaining 5 miscellaneous market events

Returns a vector of ‘event’ structs and a cursor.

use kalshi::Kalshi;
use kalshi::TradingEnvironment;
let kalshi_instance = Kalshi::new(TradingEnvironment::DemoMode, "your-key-id", "path/to/private.pem").await?;

kalshi_instance.get_multiple_events(Some(5), None, None, None, None).await.unwrap();
§Checking the User’s balance

Returns an i64 representing the user’s balance in cents.

use kalshi::Kalshi;
use kalshi::TradingEnvironment;
let kalshi_instance = Kalshi::new(TradingEnvironment::DemoMode, "your-key-id", "path/to/private.pem").await?;

kalshi_instance.get_balance();

Structs§

AmendOrderResponse
Response from the amend_order endpoint, containing both the old and new order.
ApiKey
Represents an API key (without the secret).
ApiKeyCreated
Represents a newly created API key with its secret.
ApiKeySecret
Represents a regenerated API key secret.
Candle
Represents a candlestick data point for market analysis.
Candlestick
Represents candlestick data for event-level aggregated trading.
Communication
Represents a communication message or thread.
CreateQuoteResponse
Response from creating a new quote.
CreateRfqResponse
Response from creating a new RFQ.
DaySchedule
Represents the trading schedule for a specific day.
ErrorMsg
Event
Represents an event on the Kalshi exchange.
EventLifecycleMsg
EventMetadata
Represents additional metadata for an event.
EventPosition
A user’s position in a specific event on the Kalshi exchange.
ExchangeAnnouncement
Represents an exchange-wide announcement from Kalshi.
ExchangeSchedule
Represents the trading schedule and maintenance windows for the Kalshi exchange.
ExchangeStatus
Represents the operational status of the Kalshi exchange.
FcmPosition
Represents an FCM position (simplified version for FCM interface).
Fill
A completed transaction (a ‘fill’) in the Kalshi exchange.
FillMsg
ForecastDataPoint
Represents a single forecast data point.
ForecastPercentileHistory
Represents forecast percentile history for an event.
Kalshi
The Kalshi struct is the core of the kalshi-crate. It acts as the interface between the user and the market, abstracting away the meat of requests by encapsulating authentication information and the client itself.
KalshiWebSocket
WebSocket client for real-time Kalshi market data and trading events.
LiveData
Represents real-time live data for a milestone.
MaintenanceWindow
Represents a scheduled maintenance window for the Kalshi exchange.
Market
Represents a market on the Kalshi exchange.
MarketCandlesticks
Represents candlestick data for a specific market in batch responses.
MarketLifecycleMsg
MarketPosition
A user’s position in a specific market on the Kalshi exchange.
MarketPositionMsg
MessageEnvelope
Envelope for all WebSocket messages.
MultivariateEventCollection
Represents a multivariate event collection on the Kalshi exchange.
MultivariateLookupMsg
OkMsg
Order
Represents an order in the Kalshi exchange.
OrderCreationField
Represents the necessary fields for creating an order in the Kalshi exchange.
OrderGroup
OrderQueuePosition
Orderbook
Represents the orderbook for a market on the Kalshi exchange.
OrderbookDeltaMsg
OrderbookSnapshotMsg
Quote
Represents a quote offer.
QuoteAcceptedMsg
QuoteConfirmed
Represents a confirmed quote.
QuoteCreatedMsg
Rfq
Represents an RFQ (Request for Quote).
RfqCreatedMsg
SelectedMarket
Series
Represents a series on the Kalshi exchange.
SeriesFeeChange
Represents a fee change for a series.
Settlement
A settlement of a market position in the Kalshi exchange.
SettlementSource
Represents a settlement source for a series.
Snapshot
Represents a market snapshot at a specific point in time.
SportsFilters
Represents available filters for sports markets.
StandardHours
Represents the standard trading hours for the Kalshi exchange.
StructuredTarget
Represents a structured target market.
SubscribeResponse
SubscribedMsg
Subscription
Represents an active subscription.
TickerMsg
Trade
Represents a trade executed on the Kalshi exchange.
TradeMsg
UserDataTimestamp
Represents the timestamp of the last portfolio data refresh.
VolumeIncentive
Represents a volume incentive program.

Enums§

Action
This enum is used to specify the type of action a user wants to take in an order, either buying or selling.
Channel
Available WebSocket subscription channels.
CommandResponse
Response from a WebSocket command.
KalshiError
A comprehensive set of errors that might occur in the Kalshi module.
MarketLifecycleEvent
MarketStatus
Represents the possible statuses of a market.
MveFilter
Filter for multivariate events (MVE) in market queries.
OrderStatus
The status of an order in the Kalshi exchange.
OrderType
Defines the type of an order in the Kalshi exchange.
RequestError
Specific kinds of HTTP request errors encountered in the Kalshi module.
SelfTradePreventionType
Specifies the self-trade prevention behavior for an order.
SettlementResult
Represents the possible settlement results for a market.
Side
The side of a market position in the Kalshi exchange.
TimeInForce
Specifies the time-in-force behavior for an order.
TradingEnvironment
Defines the trading environment for the Kalshi exchange.
UpdateAction
WebSocketMessage
Unified WebSocket message type.

Type Aliases§

Collection
Represents a multivariate event collection on the Kalshi exchange.
LookupEntry
Represents a lookup entry in a collection’s history.
Milestone
We don’t yet have a public schema; store raw JSON.