Kalshi ====== .. meta:: :description: Build and backtest Kalshi prediction market trading bots in Python with LumiBot using Kalshi, KalshiData, KalshiBacktesting, and built-in AI prediction tools. LumiBot supports **Kalshi** prediction-market trading and backtesting through the ``Kalshi`` broker, ``KalshiData`` data source, and ``KalshiBacktesting`` historical backtester. A Kalshi contract is a ``prediction_contract`` asset priced between ``0`` and ``1`` in USD collateral with an explicit ``outcome`` side (``"yes"`` or ``"no"``). .. include:: _snippets/botspot_mcp_callout.rst Quick Start ----------- Configure Kalshi via environment variables (demo mode is the default): .. code-block:: bash export TRADING_BROKER=kalshi export KALSHI_API_KEY_ID="your-kalshi-api-key-id" export KALSHI_PRIVATE_KEY_PATH="/path/to/kalshi-private-key.pem" # Or pass inline PEM text via KALSHI_PRIVATE_KEY export KALSHI_IS_DEMO=true Demo and production keys belong to separate Kalshi environments. Verify your account read-only without placing any orders: .. code-block:: bash python -m lumibot.example_strategies.kalshi_account_check See :doc:`environment_variables` for optional subaccount, fund-pool, and data-source settings. Creating Kalshi Contract Assets ------------------------------- Identify a market by its native Kalshi ticker and select either the YES or NO outcome: .. code-block:: python from lumibot.entities import Asset yes_asset = Asset("", Asset.AssetType.PREDICTION_CONTRACT, outcome="yes") no_asset = Asset("", Asset.AssetType.PREDICTION_CONTRACT, outcome="no") Inside any ``Strategy``, call ``get_quote``, ``get_last_price``, ``get_historical_prices``, ``create_order``, ``submit_order``, ``modify_order``, ``cancel_order``, ``get_orders``, and ``get_positions`` as usual. Buying NO buys the NO outcome; selling NO closes a NO holding. Because Kalshi nets opposite outcomes in an account, buying NO against an existing YES holding first reduces the YES exposure. Discovering Markets and Settlement Rules ---------------------------------------- Use the broker's data source (``self.broker.data_source``) to search open markets, read settlement criteria, and inspect parent events: .. code-block:: python from lumibot.entities import Asset data = self.broker.data_source markets = data.search_markets(query="Bitcoin", limit=5) if markets: selected = markets[0] rules = data.get_market_rules(selected) event = data.get_event(event_id=selected["event_ticker"]) yes_asset = Asset.from_dict(selected["outcome_assets"][0]) quote = self.get_quote(yes_asset) Topic searches match Kalshi's native series titles, tickers, and tags, then read market pages for executable tickers. Native filters (``series_ticker``, ``event_ticker``, and ``status``) are also supported. Public discovery and market-data reads use the configured environment without sending private credentials. Modifying Orders and Exchange Balances -------------------------------------- - **Order amendment:** call ``self.modify_order(order, limit_price=..., quantity=...)`` to amend an active Kalshi limit order. ``quantity`` is the updated total including existing fills, not an incremental buy. - **Cold-restart ownership:** LumiBot encodes the selected outcome and a normalized strategy-tag digest into a deterministic UUID client reference so restarted strategies recognize their own orders and restore YES/NO pricing. - **Exchange balances:** Kalshi splits collateral across exchange balances. An aggregate account balance does not guarantee that a specific market's exchange balance is funded; fund the appropriate balance via Kalshi's account controls before trading. AI Agent Prediction-Market Tools -------------------------------- When a strategy runs with ``Kalshi``, ``KalshiData``, or ``KalshiBacktesting``, LumiBot automatically exposes four built-in prediction-market agent tools (and hides them on non-prediction brokers to keep prompts focused): - ``prediction_discover_markets``: search open prediction markets and events with settlement rules (redacting future prices and unsettled outcomes during backtests). - ``prediction_get_market``: read one contract's metadata, settlement rules, YES/NO quotes, and orderbook liquidity. - ``prediction_quote``: read current YES and/or NO bid, ask, mid, spread, last price, and sizes. - ``prediction_submit_order``: submit a limit or market YES/NO order (only exposed when ``allow_trading=True``). See :doc:`agents_builtin_tools` for full tool parameters and backtest safety details. Backtesting with ``KalshiBacktesting`` -------------------------------------- ``KalshiBacktesting`` simulates historical Kalshi strategies using completed minute, hour, or daily candles, historical bid/ask quotes, and cash settlement. Public historical candle reads require no private trading key: .. code-block:: python from datetime import datetime from lumibot.backtesting import KalshiBacktesting from lumibot.entities import Asset from lumibot.strategies import Strategy class KalshiMeanReversion(Strategy): parameters = {"ticker": ""} def initialize(self): self.sleeptime = "1H" self.set_market("24/7") def on_trading_iteration(self): yes = Asset(self.parameters["ticker"], Asset.AssetType.PREDICTION_CONTRACT, outcome="yes") quote = self.get_quote(yes) if quote is None or quote.ask is None: return if quote.ask <= 0.35 and self.get_position(yes) is None: order = self.create_order(yes, 10, "buy", limit_price=quote.ask) self.submit_order(order) if __name__ == "__main__": KalshiMeanReversion.backtest( KalshiBacktesting, datetime(2026, 1, 1), datetime(2026, 2, 1), ) Depth, queue priority, and full exchange fee schedules remain approximations in backtesting. Frequently asked questions -------------------------- Does Kalshi support demo paper trading in LumiBot? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Yes. ``KALSHI_IS_DEMO=true`` is the default. Kalshi demo and production accounts use separate API keys, so configure your demo key ID and private key first when testing. How do I choose between YES and NO contracts? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pass ``outcome="yes"`` or ``outcome="no"`` when creating an ``Asset`` with ``asset_type=Asset.AssetType.PREDICTION_CONTRACT``. Both outcomes share the market ticker while keeping distinct LumiBot ``Asset`` identities. Can I backtest a Kalshi strategy without private trading keys? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Yes. ``KalshiBacktesting`` reads public historical completed candles and market metadata without requiring private order-signing credentials. Can AI agents discover and trade Kalshi markets? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Yes. On Kalshi brokers and backtests, LumiBot automatically attaches ``prediction_discover_markets``, ``prediction_get_market``, ``prediction_quote``, and ``prediction_submit_order`` (when ``allow_trading=True``) to your AI agents. How do I amend an open Kalshi limit order? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Call ``self.modify_order(order, limit_price=..., quantity=...)``. Pass the new total order quantity including any partial fills already executed, rather than an additional delta. What happens if I buy NO while holding YES? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Kalshi nets opposite outcomes within the same market, so buying NO against an open YES position reduces the YES position first before establishing net NO exposure.