Kalshi Command Center
A complete command-line interface for Kalshi prediction market trading. Provides portfolio visibility, live market scanning, trade execution, and risk management through a unified command API.
Overview
The Kalshi Command Center bridges your OpenClaw AI assistant with Kalshi's API. Core capabilities:
- - Portfolio Management: Real-time P&L tracking with emoji-annotated positions
- Live Market Scanning: Heuristic edge scoring across 600+ open markets
- Market Queries: Fetch live bid/ask data before trading
- Trade Execution: Buy/sell with Kelly sizing, risk validation, and audit logging
- Risk Management: Hard caps on trade size, position count, and daily loss
- Research Cache: Store opportunity rankings for quick reference
Available Commands
All commands are exposed through kalshi_commands.py with argparse routing. Use the module directly or import individual handlers.
Portfolio & Positions
CODEBLOCK0
Output: Cash balance, open positions with P&L, cost basis, and current value. Positions sorted by absolute P&L. Emoji indicators: 🔥 (>20% gain), ✅ (>5% gain), 📉 (break-even), ⚠️ (>15% loss).
Example:
CODEBLOCK1
Live Market Scanning
CODEBLOCK2
Output: Top 8 markets ranked by heuristic edge score. Shows bid/ask, spread (%), volume, OI, days to expiration, and composite score.
Heuristic Scoring Algorithm:
- - Spread tightness (25% weight): Markets with tight spreads = better price discovery
- Distance from extremes (35% weight): Markets in 20-80 range = actionable
- Liquidity (25% weight): Volume + Open Interest, log-scaled
- Time value (15% weight): Sweet spot 14-60 days to close
See references/scoring.md for detailed algorithm.
Example:
CODEBLOCK3
Market Data Queries
CODEBLOCK4
Output: Live bid/ask for both YES and NO sides, last price, 24h volume, status, and actionable guidance.
Example:
CODEBLOCK5
Cached Opportunities
CODEBLOCK6
Output: Top 8 opportunities from research cache with live price refresh. Shows source, edge %, confidence, and reasoning.
Order Management
CODEBLOCK7
Trade Execution
Direct trade placement (low-level):
CODEBLOCK8
Intelligent execution from cache (high-level):
CODEBLOCK9
The execute handler:
- 1. Looks up the pick from research cache
- Fetches live market data
- Calculates Kelly-sized position (if available)
- Validates risk limits
- Places the order with audit logging
Brier Score Calibration
CODEBLOCK10
Prerequisites
System Requirements
API SDK
CODEBLOCK11
Authentication & Configuration
Set environment variables OR edit your OpenClaw config:
Option 1: Environment Variables
CODEBLOCK12
Option 2: Config File (~/.openclaw/config.yaml)
CODEBLOCK13
Key Path Resolution:
- 1. If
private_key_file is set: expand as ~/.openclaw/keys/{value} if relative - Fallback to
private_key_path (legacy, deprecated) - Try standard paths if neither set
Optional: Kelly Position Sizing & Risk Validation
If available, the execute handler will use:
- -
proactive.triggers.kelly_size for position sizing - INLINECODE8 for risk gate approval
If modules are unavailable, defaults to:
- - Quantity: 10 contracts (fallback)
- Risk validation: disabled (log-only)
Market Filtering
Blocked Categories
The scanner excludes these categories automatically:
- - Weather: KXTEMP, KXRAIN, KXSNOW, KXWIND, KXWEATH (irrational/unhedgeable)
- Entertainment: KXCELEB, KXMOVIE, KXYT, KXTIKTOK (low signal)
- Social Media: KXTWIT, KXSTREAM (low volume)
- Index Futures: INX, NASDAQ, FED-MR (not Kalshi core)
See references/blocklist.md for complete list.
Sports Filter
Sports markets are intentionally excluded from the production stack. Recent evaluation did not show durable model edge there, so the system does not route sports markets into scanning or execution.
Time Window
- - Default scan: 7-180 days to expiration (interactive trading sweet spot)
- Includes volume floor (>10 contracts traded)
- Markets with tight spreads and high OI ranked first
Risk Limits
Hard caps enforced on all trades:
| Limit | Value | Enforced By |
|---|
| Max single trade cost | $25.00 USD | INLINECODE9 |
| Max position size |
100 contracts |
_check_risk() |
| Max daily loss | $50.00 USD | Kelly sizing + risk validator (if available) |
Trade Audit Log: All trades (accepted/blocked/failed) logged to ~/.openclaw/logs/trades.jsonl.
Example audit entry:
CODEBLOCK14
See references/risk-limits.md for full risk framework.
Heuristic Edge Scoring
The scan command ranks markets by a 4-factor composite score:
1. Spread Tightness (25% weight)
CODEBLOCK15
- - Score 1.0 at 0% spread (mid = bid = ask)
- Score 0.5 at 10% spread
- Score 0.0 at 20%+ spread
Rationale: Tight spreads = more efficient price discovery, easier entry/exit.
2. Distance from Extremes (35% weight)
CODEBLOCK16
- - Score 1.0 at exactly 50¢ (maximum uncertainty)
- Score 0.5 at 25¢ or 75¢ (moderate certainty)
- Score 0.0 at 0¢ or 100¢ (resolved)
- Heavy penalty (<30% of base score) for near-settled markets
Rationale: Markets in the 20-80 range offer actionable edge. Extremes are near-certain and illiquid.
3. Liquidity (25% weight)
CODEBLOCK17
Log-scaled to avoid mega-markets dominating. Weights recent volume (60%) over open interest (40%).
4. Time Value (15% weight)
CODEBLOCK18
- - Sweet spot: 14-60 days to close (score 1.0)
- Below 14d: linear ramp (less time = lower score)
- Above 60d: logarithmic decay (floor 0.3)
Rationale: Too-short markets have liquidity spikes; too-long markets lack catalysts. 14-60d is where directional bets play out.
Composite Score
CODEBLOCK19
Weighted sum of 0-100 scale. Top 8 markets by score displayed.
See references/scoring.md for worked examples.
Output Formatting
All output strips Markdown for iMessage compatibility. Emoji indicators:
| Emoji | Meaning |
|---|
| 📈 | Positive P&L or bullish signal |
| 📉 |
Negative P&L or bearish signal |
| 🔥 | High gains (>20%) or strong edge |
| ✅ | Moderate gains (>5%) or approved |
| ⚠️ | Warning (>15% loss) or risk issue |
| 🔻 | Moderate loss (>0%) |
| ➖ | Break-even |
| 🎯 | Live scan results |
| 🏀 | Sports excluded / blocked |
| 💵 | Cash/financial data |
| 📊 | Market data |
| 📎 | Ticker link |
| 💰 | Proceeds/proceeds |
Error Handling & Retry Logic
The _get_client() function retries on transient failures:
CODEBLOCK20
Failure Classification:
- -
network: Timeout, connection reset → retry with 2s backoff - INLINECODE15 : 401/403, invalid key → fail immediately
- INLINECODE16 : 429 → retry with backoff
- INLINECODE17 : Other errors → fail immediately
User-Facing Messages:
- - Network: "Can't reach Kalshi API — network timeout or connection reset."
- Auth: "Kalshi auth failed — API key may be expired or invalid."
- Rate limit: "Kalshi rate limited — too many requests. Try again in a minute."
Usage Examples
Daily Portfolio Check
CODEBLOCK21
Returns cash, positions, total P&L with emoji-coded performance.
Find New Edge Right Now
CODEBLOCK22
Scans 600 markets, ranks by heuristic score, shows top 8 with bid/ask and days to close.
Check Before Buying
CODEBLOCK23
Live bid/ask, spread, volume, and guidance on limit price strategy.
Execute from Research Cache
CODEBLOCK24
Looks up pick #1, fetches live market data, places buy order with 15 contracts (manual override skips Kelly).
Monitor Orders
CODEBLOCK25
Lists all open/resting limit orders with price and remaining count.
Exit a Position
CODEBLOCK26
Sell 10 contracts at bid (35¢).
File Structure
CODEBLOCK27
Implementation Reference
Source: kalshi_commands.py (standalone implementation)
- - Env var support for API credentials
- CLI routing via argparse
- Full retry logic and error classification
- Trade audit logging
- Kelly sizing integration (optional)
- Risk validation gates (optional)
Key Functions (all available in kalshi_commands.py):
- -
portfolio_command() — cash + positions + P&L - INLINECODE21 — live scan with heuristic scoring
- INLINECODE22 — cached research results
- INLINECODE23 — live bid/ask for single market
- INLINECODE24 ,
sell_command() — direct order placement - INLINECODE26 — intelligent execution from cache
- INLINECODE27 — list resting orders
- INLINECODE28 — cancel by order ID
- INLINECODE29 — API client with retry logic
- INLINECODE30 — user-friendly error messages
Troubleshooting
"Kalshi is not enabled"
Set kalshi.enabled: true in ~/.openclaw/config.yaml.
"Kalshi key_id not configured"
Set KALSHI_KEY_ID env var OR kalshi.api_key_id in config file.
"Kalshi private key not found"
Set KALSHI_KEY_PATH env var (absolute path) OR kalshi.private_key_file in config.
"Auth failed — API key may be expired"
Verify key and private key file exist and are readable. Check Kalshi account for key status.
"Can't reach Kalshi API — network timeout"
Transient network issue or Kalshi infrastructure down. Retry in 30s.
"Kalshi rate limited — too many requests"
Back off for 1 minute. The scanner makes ~50-100 API calls per scan.
No markets after filtering
All 600 open markets filtered out by spread/volume/timeframe. This stack intentionally excludes sports; try widening your non-sports filters instead.
Advanced Usage
Custom Ticker Names
Edit ~/.openclaw/config.yaml:
CODEBLOCK28
All commands will use friendly names in output.
Audit Log Inspection
Trade execution is fully logged to ~/.openclaw/logs/trades.jsonl:
CODEBLOCK29
Parse to monitor trade velocity, P&L, and blocked trades.
Dry-Run Scanning
To scan without placing orders:
CODEBLOCK30
OpenClaw Ecosystem Integration
The Kalshi Command Center is your execution layer in the Prediction Market Trading Stack.
| Connected Skill | How It Connects |
|---|
| Kalshalyst | Feeds edge opportunities → execute trades via execute command |
| Market Morning Brief |
Reads your portfolio for the daily P&L digest |
|
Portfolio Drift Monitor | Monitors positions you open through this command center |
|
Prediction Market Arbiter | Flags cross-platform divergences → trade on the Kalshi side here |
Install the complete stack:
CODEBLOCK31
Agent Bug-Fix Protocol
CRITICAL: When you (the agent) discover and fix a bug in any script during a conversation, you MUST write the fix to the source file on disk using file editing tools. Showing the fix in chat is NOT sufficient — the next scheduled run starts a fresh session and will not have your conversational fix.
Checklist after finding a bug:
- 1. Edit the actual
.py file on disk (e.g., ~/skills/kalshi-command-center/scripts/kalshi_commands.py) - Also update the installed copy at INLINECODE42
- Confirm both files are written before telling the user the fix is done
- If the fix is significant, stage a git commit in INLINECODE43
Never say "fixed" if you only demonstrated the fix in conversation output.
Attribution
Author: KingMadeLLC
Version: 1.0.0
Feedback & Issues
Found a bug? Have a feature request? Want to share results?
Part of the OpenClaw Prediction Stack — the first prediction market skill suite on ClawHub.
Kalshi 指挥中心
一个用于Kalshi预测市场交易的完整命令行界面。通过统一的命令API提供投资组合可见性、实时市场扫描、交易执行和风险管理。
概述
Kalshi 指挥中心将您的 OpenClaw AI 助手与 Kalshi 的 API 连接起来。核心功能:
- - 投资组合管理:实时盈亏追踪,带表情符号标注的持仓
- 实时市场扫描:对600+开放市场进行启发式评分
- 市场查询:交易前获取实时买卖报价
- 交易执行:使用凯利公式进行买卖,风险验证和审计日志
- 风险管理:对交易规模、持仓数量和每日亏损设置硬上限
- 研究缓存:存储机会排名以便快速参考
可用命令
所有命令通过 kalshi_commands.py 暴露,使用 argparse 路由。直接使用模块或导入各个处理器。
投资组合与持仓
bash
python kalshi_commands.py portfolio
python kalshi_commands.py positions
输出:现金余额、持仓(含盈亏)、成本基础和当前价值。持仓按绝对盈亏排序。表情符号指示:🔥(>20%收益)、✅(>5%收益)、📉(盈亏平衡)、⚠️(>15%亏损)。
示例:
📈 盈亏:3个持仓共+$42.50
💵 现金:$1,234.56 · 已部署:$123.45 · 价值:$165.95
🔥 美国通胀会超过4%吗?:10x YES @ $50.00 → $62.50 (+25%)
✅ 科技市场收益:5x NO @ $40.00 → $42.10 (+5%)
➖ 政治不确定性:25x YES @ $25.00 → $25.00 (0%)
实时市场扫描
bash
python kalshi_commands.py scan # 宏观/默认市场
输出:按启发式评分排名前8的市场。显示买卖价、价差(%)、成交量、未平仓合约、到期天数和综合评分。
启发式评分算法:
- - 价差紧密度(25%权重):价差紧的市场 = 更好的价格发现
- 距离极端值(35%权重):20-80范围内的市场 = 可操作
- 流动性(25%权重):成交量 + 未平仓合约,对数缩放
- 时间价值(15%权重):最佳区间14-60天到期
详细算法见 references/scoring.md。
示例:
🎯 实时扫描 — 扫描600个市场,47个通过筛选:
- 1. 美国通胀会超过4%吗?
35¢/37¢(价差2¢ = 5.8%)| 成交量 1,234 | 未平仓 5,678 | 45天
评分:78.5 | ECON-INFL-2026
- 2. 本季度科技板块反弹?
42¢/44¢(价差2¢ = 4.8%)| 成交量 892 | 未平仓 3,456 | 60天
评分:75.2 | TECH-Q1-2026
市场数据查询
bash
python kalshi_commands.py get TICKER
输出:YES和NO双方的实时买卖价、最新价格、24小时成交量、状态和可操作建议。
示例:
📊 美国通胀会超过4%吗?(ECON-INFL-2026)
状态:开放 | 关闭:2026-04-15
YES — 买价:35¢ | 卖价:37¢ | 价差:2¢
NO — 买价:63¢ | 卖价:65¢ | 价差:2¢
最新:35¢ | 24小时成交量:1,234 | 总成交量:12,345
💡 要卖出YES合约:以yes_bid(35¢)卖出可立即成交,或以36¢挂卖价获得更好价格。
缓存机会
bash
python kalshi_commands.py markets # 宏观为主的默认设置
python kalshi_commands.py markets all # 缓存中的所有内容
输出:研究缓存中排名前8的机会,附带实时价格刷新。显示来源、优势百分比、置信度和推理。
订单管理
bash
python kalshi_commands.py orders # 列出所有开放/挂单
python kalshicommands.py cancel ORDERID
交易执行
直接交易下单(低级):
bash
python kalshi_commands.py buy TICKER yes 10 35 # 以35¢买入10份YES
python kalshi_commands.py sell TICKER no 5 63 # 以63¢卖出5份NO
从缓存智能执行(高级):
bash
python kalshi_commands.py execute 1 # 使用凯利公式买入选择#1
python kalshi_commands.py execute 2 qty 25 # 手动25份合约买入选择#2
python kalshi_commands.py execute 3 15 contracts # 手动覆盖买入选择#3
execute 处理器:
- 1. 从研究缓存中查找选择
- 获取实时市场数据
- 计算凯利公式规模(如果可用)
- 验证风险限制
- 下单并记录审计日志
布赖尔评分校准
bash
python kalshi_commands.py brier # 90天完整报告
python kalshi_commands.py brier claude # 按Claude估计器筛选
python kalshi_commands.py brier 30 # 30天回溯
前提条件
系统要求
API SDK
bash
pip install kalshi-python
认证与配置
设置环境变量或编辑您的 OpenClaw 配置:
选项1:环境变量
bash
export KALSHIKEYID=your-api-key-id
export KALSHIKEYPATH=/path/to/your/private.key
选项2:配置文件(~/.openclaw/config.yaml)
yaml
kalshi:
enabled: true
apikeyid: your-key-id
privatekeyfile: keys/kalshi-private.key # 相对于 ~/.openclaw
# 可选:常用代码的友好名称
ticker_names:
ECON-INFL-2026: 美国通胀会超过4%吗?
TECH-Q1-2026: 本季度科技板块反弹?
密钥路径解析:
- 1. 如果设置了 privatekeyfile:如果是相对路径,则扩展为 ~/.openclaw/keys/{value}
- 回退到 privatekeypath(旧版,已弃用)
- 如果两者都未设置,尝试标准路径
可选:凯利公式仓位规模与风险验证
如果可用,execute 处理器将使用:
- - proactive.triggers.kellysize 进行仓位规模计算
- proactive.triggers.validaterisk 进行风险门控批准
如果模块不可用,默认:
- - 数量:10份合约(回退)
- 风险验证:禁用(仅记录)
市场筛选
屏蔽类别
扫描器自动排除以下类别:
- - 天气:KXTEMP、KXRAIN、KXSNOW、KXWIND、KXWEATH(非理性/不可对冲)
- 娱乐:KXCELEB、KXMOVIE、KXYT、KXTIKTOK(低信号)
- 社交媒体:KXTWIT、KXSTREAM(低成交量)
- 指数期货:INX、NASDAQ、FED-MR(非Kalshi核心)
完整列表见 references/blocklist.md。
体育筛选
体育市场被有意排除在生产栈之外。最近的评估未显示持久的模型优势,因此系统不会将体育市场路由到扫描或执行中。
时间窗口
- - 默认扫描:7-180天到期(交互式交易最佳区间)
- 包含成交量下限(>10份合约交易)
- 价差紧且未平仓合约高的市场排名靠前
风险限制
所有交易强制执行硬上限:
| 限制 | 值 | 执行者 |
|---|
| 单笔最大交易成本 | $25.00 USD | checkrisk() |
| 最大持仓规模 |
100份合约 |
checkrisk() |
| 每日最大亏损 | $50.00 USD | 凯利公式规模 + 风险验证器(如果可用) |
交易审计日志:所有交易(已接受/已阻止/失败)记录到 ~/.openclaw/logs/trades.jsonl。
审计条目示例:
json
{
timestamp: 2026-02-26T