# Automated Prediction Market Trading: How CLI Agents Place Orders on Kalshi
Prediction markets have crossed a threshold. What was once a niche corner of crypto-adjacent speculation is now a regulated, liquid venue where serious capital moves on Fed decisions, oil price ceilings, and recession probabilities. Kalshi — the first CFTC-regulated prediction market exchange in the US — has made it possible to trade event contracts with real money, real settlement, and an actual API.
The natural next step for any quantitatively inclined trader is automation. Not alerts, not dashboards — actual agents that read market state, evaluate a thesis, and place orders without human intervention. This post covers how that works in practice, with specific attention to the CLI-driven workflow that's become the most practical entry point for developers building on Kalshi.
---
## Why CLI Agents Make Sense for Prediction Markets
Prediction market trading is fundamentally different from equity or crypto trading. The edge rarely comes from latency or order book microstructure — it comes from information synthesis. You're asking: *does the current price reflect what I believe the probability of this event actually is?*
That makes prediction markets a natural fit for **thesis-driven agents** — programs that encode a belief, monitor the relevant market, and execute when there's a meaningful gap between your probability estimate and the market price.
CLI agents are well-suited for this because:
- **They're composable.** You can pipe market data into external models, trigger agents from cron jobs, or chain commands in shell scripts.
- **They're transparent.** Unlike GUI platforms, CLI output is easy to log, grep, and audit.
- **They're fast to iterate on.** Changing your thesis means changing a config or a prompt — not rebuilding a UI.
The tooling around this has matured significantly. [SimpleFunctions](https://simplefunctions.dev) is the most complete agentic runtime built specifically for Kalshi and Polymarket, offering a CLI, MCP server, REST API, and Telegram integration in a single package.
---
## Installing the SimpleFunctions CLI
The CLI is distributed via npm and installs globally:
npm install -g @spfunctions/cli
Once installed, you'll authenticate with your Kalshi API credentials. SimpleFunctions handles the OAuth flow and stores credentials locally so subsequent commands don't require re-auth.
sf auth login
From here, you have access to four primary commands: `sf scan`, `sf agent`, `sf positions`, and `sf dashboard`. Each maps to a distinct phase of the trading workflow.
---
## Understanding the Core Commands
### `sf scan` — Market Discovery and Screening
`sf scan` queries active Kalshi markets and filters them against criteria you define. This is where you find opportunities before deploying capital.
sf scan --category ECONOMICS --min-volume 50000 --max-spread 0.04
This returns active economic markets with at least $50k in volume and a bid-ask spread under 4 cents. You can also scan by series ticker:
sf scan --series KXFEDDECISION
The `KXFEDDECISION` series covers Federal Reserve interest rate decisions. Each contract resolves based on whether the Fed raises, holds, or cuts rates at a given FOMC meeting. Running this scan during the week before an FOMC meeting typically surfaces multiple active contracts with meaningful volume.
Other tickers worth scanning regularly:
- **`KXWTIMAX`** — WTI crude oil monthly maximum price contracts. These are useful when you have a view on supply disruptions or demand shocks.
- **`KXRECSSNBER`** — NBER recession determination contracts. Longer time horizon, but high information density around macro inflection points.
- **`KXCPI`** — CPI release outcome contracts. Extremely active around monthly inflation prints.
sf scan --series KXWTIMAX --output json | jq '.markets[] | {ticker, yes_bid, no_bid, volume}'
Piping to `jq` lets you process market data in shell scripts or feed it into downstream analysis.
### `sf agent` — Thesis-Driven Order Placement
This is the core of the automation layer. `sf agent` takes a thesis — a structured description of your belief about a market — evaluates current market prices against that thesis, and places orders when the edge exceeds a configurable threshold.
sf agent run --market KXFEDDECISION-25JUN-B5.25 --thesis "Fed holds at 5.25-5.5% in June given persistent core services inflation" --edge-threshold 0.06
The agent workflow, under the hood:
1. Fetches current order book and last-trade price for the specified market
2. Evaluates the thesis against current price (using an internal LLM call or a user-supplied probability)
3. Calculates implied edge: `|thesis_probability - market_price|`
4. If edge exceeds threshold, constructs and submits a limit order at a configurable offset from the best bid/ask
5. Logs the order, confirmation, and reasoning to stdout (and optionally to a file or webhook)
You can also supply an explicit probability rather than relying on LLM-derived estimates:
sf agent run \
--market KXWTIMAX-25JUL-B85 \
--yes-probability 0.31 \
--edge-threshold 0.05 \
--max-position 500
Here you're asserting a 31% probability that WTI hits $85 as a monthly maximum in July. If the market is pricing YES at 24 cents, the 7-point edge clears your threshold and the agent places a YES order up to $500 notional.
### `sf positions` — Portfolio Monitoring
sf positions --show-pnl --group-by series
This returns your open positions grouped by market series, with unrealized P&L calculated against current mid prices. Useful in a cron job:
# cron: every 30 minutes during market hours
*/30 9-17 * * 1-5 sf positions --show-pnl --output json >> ~/logs/positions.jsonl
### `sf dashboard` — Terminal UI
`sf dashboard` opens a live terminal dashboard with market watchlists, position summaries, and order activity. Less relevant for pure automation, but useful when you want visibility into what your agents are doing without leaving the terminal.
---
## Building a Practical Automated Trading Workflow
Let's walk through a concrete example: automating trades around FOMC decisions.
### Step 1: Define Your Model
Before writing a single command, you need a thesis model. For FOMC markets, that might mean:
- Tracking the CME FedWatch implied probabilities daily
- Maintaining your own Bayesian update on rate path based on CPI, PCE, and employment data
- Setting a calibrated probability for each FOMC outcome
This doesn't have to be ML-heavy. A simple spreadsheet model that you update weekly and export as JSON is sufficient.
### Step 2: Scan for Active Contracts
sf scan --series KXFEDDECISION --output json > fomc_markets.json
Parse this to find contracts for the upcoming meeting and note their tickers.
### Step 3: Run Agent Evaluation
With a shell script that reads your model output:
#!/bin/bash
# fomc_agent.sh
MARKET="KXFEDDECISION-25JUL-B5.25"
MY_PROB=$(cat model_output.json | jq '.hold_probability')
sf agent run \
--market $MARKET \
--yes-probability $MY_PROB \
--edge-threshold 0.05 \
--max-position 1000 \
--dry-run # remove this flag to go live
The `--dry-run` flag lets you validate the agent's reasoning and intended order before live execution. This is critical when first deploying any automation.
### Step 4: Monitor and Adjust
sf positions --filter-series KXFEDDECISION --show-pnl
If a position moves significantly against you, you can set stop-loss logic using the agent's `--exit-on-loss` parameter or handle it in a wrapper script that calls `sf agent exit`.
---
## Working with the MCP Server and REST API
For more complex integrations — connecting to external data sources, building multi-agent systems, or embedding prediction market signals into existing trading infrastructure — SimpleFunctions exposes an MCP (Model Context Protocol) server and a REST API.
The MCP server is particularly useful if you're building on top of Claude or another LLM that supports tool use. It exposes Kalshi market data and order placement as callable tools, which means your LLM can query live market prices mid-reasoning and place orders based on that context.
The REST API mirrors the CLI functionality with standard JSON request/response patterns. See the [SimpleFunctions API docs](https://simplefunctions.dev/docs) for endpoint reference and authentication details.
For teams running multiple agents simultaneously — say, one for macro economic contracts and another for weather or geopolitical markets — the API makes it straightforward to centralize logging, position management, and risk limits.
---
## Risk Management Considerations
Automation in prediction markets introduces the same failure modes as any algorithmic trading system, with a few unique wrinkles worth addressing explicitly.
**Thesis staleness.** A thesis encoded in a config file from three weeks ago may no longer reflect reality. Build timestamp validation into your agent scripts and require explicit re-approval of theses older than N days before live execution.
**Liquidity assumptions.** Markets like `KXRECSSNBER` can have wide spreads and low volume relative to something like `KXFEDDECISION`. An agent placing limit orders in a thin book may move prices against itself or fail to fill entirely. Always inspect the order book depth before setting position size parameters.
sf scan --market KXRECSSNBER-25-Y --show-depth
**Correlated positions.** If you're running agents across multiple macro markets simultaneously, be aware that Fed rate decisions, CPI outcomes, and recession contracts are highly correlated. Position limits set per-market may understate your actual portfolio risk.
**Settlement ambiguity.** Kalshi contracts have specific resolution criteria that don't always map cleanly to how economic data is reported. The `KXRECSSNBER` contracts, for instance, resolve on NBER's *official* recession determination — which can lag the actual economic turning point by 12-18 months. Make sure your thesis accounts for the resolution mechanism, not just the underlying economic outcome.
---
## Telegram Bot Integration
For traders who want mobile visibility without building a full frontend, SimpleFunctions includes a Telegram bot that surfaces position updates, order confirmations, and agent activity.
Once configured, your agent workflow emits notifications at key events:
- Order submitted
- Order filled (partial or complete)
- Position P&L crossing a threshold
- Agent skipping a trade with reason logged
This is particularly useful for overnight or weekend agents running on scheduled jobs where you want awareness without being tethered to a terminal.
---
## Getting Deeper into the Tooling
If you're building a more sophisticated system — custom scoring models, multi-market portfolio optimization, or integration with external data pipelines — the [SimpleFunctions documentation](https://simplefunctions.dev/docs/guide) covers advanced configuration, agent chaining, and the full parameter surface for each CLI command.
A few areas worth exploring beyond the basics:
- **Custom scoring functions**: Supply your own probability estimates via stdin or config rather than using the built-in LLM evaluation
- **Batch agent runs**: Execute thesis evaluation across multiple markets simultaneously with parallelism controls
- **Webhook callbacks**: Trigger external systems when agents take specific actions — useful for integrating with portfolio management or logging infrastructure
---
## What This Doesn't Replace
It's worth being direct about limitations. CLI agents are good at executing a thesis you've already formed. They don't generate theses from scratch, they don't have reliable access to real-time news unless you wire that in explicitly, and they can't replace the judgment required to evaluate resolution criteria edge cases.
The value is in discipline and speed: executing consistently against a model rather than second-guessing yourself mid-market, and doing it fast enough to capture edge before it closes. For macro markets like FOMC decisions, where prices can move 3-5 points in minutes around data releases, having automation that executes on a pre-committed probability estimate is a meaningful operational advantage.
Prediction market automation is still early. The tooling is functional, the regulatory environment is clarifying, and the number of sophisticated participants is small relative to traditional markets. That combination is exactly when systematic approaches tend to compound.
---
*SimpleFunctions is available at [simplefunctions.dev](https://simplefunctions.dev). Install the CLI with `npm install -g @spfunctions/cli` and authenticate with your Kalshi API credentials to start.*