{"id":50213540,"url":"https://github.com/octagonai/kalshi-trading-bot-cli","last_synced_at":"2026-05-26T07:02:34.024Z","repository":{"id":305782859,"uuid":"1019798802","full_name":"OctagonAI/kalshi-trading-bot-cli","owner":"OctagonAI","description":"AI-native CLI for trading Kalshi prediction markets. Runs deep fundamental research, generates independent probability estimates, computes edge vs. live order books, and executes trades with Kelly sizing and a 5-gate risk engine. ","archived":false,"fork":false,"pushed_at":"2026-05-26T01:39:39.000Z","size":5967,"stargazers_count":302,"open_issues_count":9,"forks_count":78,"subscribers_count":9,"default_branch":"main","last_synced_at":"2026-05-26T02:27:15.926Z","etag":null,"topics":["ai-trading-bots","deep-research","deep-trading","kalshi","polymarket","prediction-markets","trading"],"latest_commit_sha":null,"homepage":"https://octagonai.co/markets/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/OctagonAI.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null}},"created_at":"2025-07-14T22:29:07.000Z","updated_at":"2026-05-25T13:51:06.000Z","dependencies_parsed_at":"2025-07-22T02:38:38.134Z","dependency_job_id":"05b47490-579c-429a-b430-0fe46b9f666a","html_url":"https://github.com/OctagonAI/kalshi-trading-bot-cli","commit_stats":null,"previous_names":["octagonai/kalshi-deep-trading-bot","octagonai/kalshi-trading-bot-cli"],"tags_count":7,"template":false,"template_full_name":null,"purl":"pkg:github/OctagonAI/kalshi-trading-bot-cli","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/OctagonAI%2Fkalshi-trading-bot-cli","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/OctagonAI%2Fkalshi-trading-bot-cli/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/OctagonAI%2Fkalshi-trading-bot-cli/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/OctagonAI%2Fkalshi-trading-bot-cli/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/OctagonAI","download_url":"https://codeload.github.com/OctagonAI/kalshi-trading-bot-cli/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/OctagonAI%2Fkalshi-trading-bot-cli/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33508317,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T03:12:49.672Z","status":"ssl_error","status_checked_at":"2026-05-26T03:12:47.976Z","response_time":63,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai-trading-bots","deep-research","deep-trading","kalshi","polymarket","prediction-markets","trading"],"created_at":"2026-05-26T07:02:32.391Z","updated_at":"2026-05-26T07:02:34.018Z","avatar_url":"https://github.com/OctagonAI.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Kalshi Trading Bot CLI\n\nAI-powered Kalshi trading CLI that finds edge and executes trades.\n\nRuns deep fundamental research on every market — independent probability estimates, ranked price drivers, catalyst calendars — then computes edge as the spread between model price and the live order book. Signals are sized using half-Kelly and filtered through a 5-gate risk engine before a dollar is risked.\n\nIntegrates with the [Octagon Research API](https://app.octagonai.co) for AI-generated probability estimates that power the edge detection engine.\n\n![Kalshi Trading Bot CLI](assets/screenshot.png)\n\n## Prerequisites\n\n- **[Bun](https://bun.com/) ≥ 1.1** (required — the bot uses `bun:sqlite` and runs `.tsx` directly; Node.js won't work)\n  ```bash\n  curl -fsSL https://bun.com/install | bash\n  ```\n- A **Kalshi** account with API access (API key + RSA private key)\n- One **LLM provider key** (OpenAI / Anthropic / Google / xAI / OpenRouter / Ollama). The setup wizard collects these on first run.\n- Optional: an **[Octagon](https://app.octagonai.co)** key for AI edge analysis, and a **Tavily** key for web research.\n\n## Quick Start\n\n```bash\nbunx kalshi-trading-bot-cli@latest\n```\n\nThat's it — no clone, no install. The setup wizard runs automatically on first launch and walks you through API keys.\n\nPrefer a global install? `bun add -g kalshi-trading-bot-cli` then run `kalshi`.\n\nOr work from a clone:\n\n```bash\ngit clone https://github.com/OctagonAI/kalshi-trading-bot-cli.git\ncd kalshi-trading-bot-cli\nbun install\nbun start\n```\n\n### Where things live\n\n- **Config, cache, SQLite DB:** `~/.kalshi-bot/`\n- **API keys (`.env`):** `~/.kalshi-bot/.env` — written by the setup wizard. A `.env` in the current directory takes precedence (handy for dev).\n- **First run** with no keys configured triggers the setup wizard automatically.\n\n### Updating\n\nUsing `@latest` in the `bunx` command always pulls the newest published version — so `bunx kalshi-trading-bot-cli@latest` is the zero-friction path.\n\nIf you ran `bunx kalshi-trading-bot-cli` without `@latest`, Bun may serve a cached copy. Force a refresh:\n\n```bash\nbunx kalshi-trading-bot-cli@latest   # pin latest for this invocation\nbun pm cache rm                      # or clear Bun's install cache\n```\n\nIf you installed globally with `bun add -g kalshi-trading-bot-cli`:\n\n```bash\nbun update -g kalshi-trading-bot-cli         # update in place\nbun add -g kalshi-trading-bot-cli@latest     # or reinstall pinned to latest\n```\n\nCheck your installed version with `kalshi --version` (or `bun pm ls -g | grep kalshi`).\n\n## Example Session\n\n```text\n$ bunx kalshi-trading-bot-cli@latest\n\nWelcome to Kalshi Trading Bot CLI\nType help for commands, or just ask a question.\n\n\u003e search crypto\n\n  Ticker                  Title                          Last    Volume\n  KXBTC-26APR-B95000      Bitcoin above $95k by Apr 30   $0.58   12,841\n  KXBTC-26APR-B100000     Bitcoin above $100k by Apr 30  $0.31    8,203\n  KXETH-26APR-B2000       Ethereum above $2k by Apr 30   $0.72    5,419\n\n3 markets found\n\n\u003e analyze KXBTC-26APR-B95000\n\n  Octagon Research Report — KXBTC-26APR-B95000\n  ─────────────────────────────────────────────\n  Model Probability   72%\n  Market Price        58%\n  Edge               +14.0%  (very_high confidence)\n\n  Top Drivers\n  1. Bitcoin ETF inflows accelerating            impact: high\n  2. Halving cycle momentum                      impact: high\n  3. Macro risk-on sentiment                     impact: moderate\n\n  Kelly Sizing\n  Recommended: 3 contracts YES at $0.58\n  Risk gates: ✓ Kelly  ✓ Liquidity  ✓ Correlation  ✓ Concentration  ✓ Drawdown\n\n\u003e buy KXBTC-26APR-B95000 3 58\n\n  ✓ Order placed: BUY 3 YES @ $0.58\n  Order ID: abc-123-def\n\n\u003e portfolio\n\n  Ticker                  Side  Qty  Entry   Now    Edge    P\u0026L\n  KXBTC-26APR-B95000      YES    3   $0.58   $0.61  +11.0%  +$0.09\n\n  Cash: $487.26 · Exposure: $1.74 · Positions: 1\n```\n\n## Commands\n\n| Command | Description |\n|---------|-------------|\n| `search [theme\\|ticker\\|query]` | Find markets by keyword or theme (Octagon-backed when key set) |\n| `search edge [--min-edge N]` | Scan all markets by model edge (Octagon `markets-with-edge`) |\n| `similar \u003cticker\\|\"query\"\u003e` | Semantic neighbors via Octagon embeddings |\n| `clusters [--label X]` | Browse thematic clusters of the Kalshi universe |\n| `clusters \u003cid\u003e` | List markets inside a cluster |\n| `clusters --behavioral` | Behavioral clusters by 30-day return vectors |\n| `clusters --ranked` | Rank clusters by historical basket return |\n| `peers \u003cticker\u003e` | Markets in the same cluster as a ticker |\n| `correlate \u003ct1\u003e \u003ct2\u003e [...]` | Pairwise Pearson correlation matrix |\n| `basket build` | Diversified basket with cluster + correlation caps |\n| `basket backtest` | NAV summary: total return, Sharpe, max drawdown, win rate |\n| `basket size` | Fractional Kelly sizing for picked legs |\n| `basket candles` | OHLC bars for a weighted basket NAV |\n| `basket validate` | One-call portfolio diagnostics (clusters, correlations, calendar clashes, warnings) |\n| `basket size --auto-probs` | Auto-fetch model probabilities via `markets/edge` and Kelly-size |\n| `basket backtest --theme \u003cname\u003e` | Resolve an editorial theme to a NAV basket and backtest it |\n| `series events \u003cticker\u003e` | List events inside a series |\n| `events` / `events \u003cticker\u003e` | Octagon events list + outcome ladder per event |\n| `series` / `series \u003cticker\u003e` | Kalshi series rollup (24h vol, market count) |\n| `series candles \u003cticker\u003e` | Series-level NAV (basket of top sub-markets) |\n| `catalysts upcoming --days N` | Markets closing in the next N days, grouped by week |\n| `themes` (registry) | Editorial narrative buckets — list/show/import/create/delete/add-series |\n| `themes report` | 25-theme dashboard with SEO + liquidity |\n| `themes audit` | Flag dead themes (high SEO + zero volume) |\n| `themes overlap` | Cross-theme dedupe report |\n| `analyze \u003cticker\u003e` | Deep analysis: edge, drivers, Kelly sizing |\n| `watch \u003cticker\u003e` | Live price and orderbook feed |\n| `watch --theme \u003ctheme\u003e` | Continuous theme scan |\n| `buy \u003cticker\u003e \u003ccount\u003e [price] [yes\\|no]` | Buy contracts |\n| `sell \u003cticker\u003e \u003ccount\u003e [price] [yes\\|no]` | Sell contracts |\n| `cancel \u003corder_id\u003e` | Cancel a resting order |\n| `backtest` | Model accuracy scorecard + live edge scanner |\n| `portfolio` | Positions, P\u0026L, risk snapshot |\n| `setup` | Re-run setup wizard (inside TUI) |\n| `init` | Launch setup wizard from CLI (`kalshi init`) |\n| `clear-cache` | Delete local cache and rebuild (`kalshi clear-cache`) |\n| `help [command]` | Detailed help for a command |\n\n### Flags\n\n| Flag | Description |\n|------|-------------|\n| `--json` | JSON output for scripts and agents |\n| `--refresh` | Force fresh Octagon report (analyze) |\n| `--performance` | Include win rate, Sharpe, Brier scores (portfolio) |\n| `--dry-run` | Scan without persisting edges (watch) |\n| `--verbose` | Verbose output |\n| `--min-edge \u003cn\u003e` | Minimum edge threshold in pp (backtest default 0.5) |\n| `--interval \u003cmin\u003e` | Scan interval in minutes (watch) |\n| `--live` | Force 15m scan interval (watch) |\n| `--days \u003cn\u003e` | Lookback period in days (backtest, default 15) |\n| `--max-age \u003cn\u003e` | Reject predictions older than N days (backtest, default = `--days`) |\n| `--resolved` | Resolved markets only (backtest) |\n| `--unresolved` | Open markets only (backtest) |\n| `--category \u003ccat\u003e` | Filter by category (backtest, search edge) |\n| `--limit \u003cn\u003e` | Max results to show (search edge, default 20) |\n| `--min-volume \u003cn\u003e` | Min per-contract volume (from Octagon snapshot; falls back to Kalshi lifetime if missing). Backtest default 1. |\n| `--min-price \u003cn\u003e` | Min contract price, 0-100 scale (backtest, default 5) |\n| `--max-price \u003cn\u003e` | Max contract price, 0-100 scale (backtest, default 95) |\n| `--export \u003cpath\u003e` | Export per-market CSV (backtest) |\n| `--top-k \u003cn\u003e` | Number of neighbors (similar); legs per cluster (clusters --ranked) |\n| `--behavioral` | Use behavioral clustering (clusters, peers) |\n| `--ranked` | Rank clusters by historical basket return (clusters) |\n| `--label \u003csubstr,...\u003e` | Filter by cluster label substring (clusters, basket build) |\n| `--close-before \u003ciso\u003e` | Only markets closing before this timestamp |\n| `--window-days \u003cn\u003e` | Correlation lookback (correlate; basket build) |\n| `--correlation-interval \u003c1h\\|1d\u003e` | Override candle bin size for correlate |\n| `--timeframe \u003c1w\\|1m\\|3m\\|6m\\|1y\u003e` | Window/bin size for basket commands |\n| `--weights \u003ccsv\u003e` | Comma-separated weights for basket backtest/candles |\n| `--bankroll \u003cusd\u003e` | Bankroll for Kelly sizing (basket size/build) |\n| `--kelly \u003c0-1\u003e` | Kelly multiplier (default 0.25) |\n| `-n \u003cn\u003e` | Basket size requested (basket build) |\n| `--max-per-cluster \u003cn\u003e` | Cap legs per thematic cluster (basket build) |\n| `--max-corr \u003c-1..1\u003e` | Pairwise correlation cap (basket build) |\n| `--min-return \u003cn\u003e` | Minimum total_return for clusters --ranked |\n| `--series \u003cticker\u003e` | Filter to a Kalshi series (search, similar, basket) |\n| `--sort-by \u003ckey\u003e` | Sort key for search edge: edge_pp \\| expected_return \\| total_volume \\| model_probability |\n| `--probs \u003ccsv\u003e` | Per-leg probabilities, e.g. `KX-A:0.62,KX-B:0.55` |\n| `--tickers \u003ccsv\u003e` | Comma-separated tickers (correlate, basket backtest/candles) |\n| `-q \"text\"` | Free-text anchor for similar / basket build |\n| `--show-cluster` | Print cluster membership only (peers) |\n| `--theme \u003cname\u003e` | Resolve an editorial theme to a ticker list (basket backtest/candles/validate/size) |\n| `--aggregate-by series` | Roll up search results to the series level |\n| `--active-only` | Drop non-active markets (defensive flag — open universe by default) |\n| `--series-prefix \u003cprefix\u003e` | Server-side series prefix match (e.g. `KXBTC` matches KXBTCD, KXBTCY, ...) |\n| `--sides yes,no,yes` | Per-ticker side for `correlate` (sign-flipped) |\n| `--cells` | Include per-cell detail (overlap, reason) in `correlate` |\n| `--auto-probs` | `basket size`: auto-fetch model probabilities via `markets/edge` |\n\n### Discovery \u0026 Portfolio (Octagon-powered)\n\nThe `search`, `similar`, `clusters`, `peers`, `correlate`, and `basket` commands turn the whole Kalshi universe into a queryable database. When `OCTAGON_API_KEY` is set the bot routes searches through Octagon's typed endpoints — semantic embedding lookups, nightly k-means clusters (thematic + behavioral), Pearson correlation matrices, and one-call diversified basket construction with cluster caps and pairwise-correlation gates. Without a key, `search` and `search edge` fall back to the local SQLite cache.\n\n```bash\n# Free-text + structured search (semantic full-text + filters)\nkalshi search \"bitcoin price\" --category crypto --min-volume 10000 --limit 20\n\n# Edge ranking from Octagon's latest run (server-side, no local pre-fetch)\nkalshi search edge --min-edge 5 --limit 10 --sort-by total_volume\n\n# Semantic neighbors — catches matches keyword search misses\nkalshi similar KXBTCD-26DEC31-T100000 --top-k 25\nkalshi similar -q \"Will Bitcoin pierce six figures\" --category crypto\n\n# Browse the universe by theme\nkalshi clusters --label fed                 # find Fed-decision clusters\nkalshi clusters 42                          # markets in cluster 42\nkalshi clusters --behavioral                # behavioral clusters (mean ret + vol)\nkalshi clusters --ranked --timeframe 1y --min-return 0.20 --top-k 5\n\n# Same-theme dedup\nkalshi peers KXBTCD-26DEC31-T100000 --kind thematic --limit 50\nkalshi peers KXBTCD-26DEC31-T100000 --show-cluster     # which cluster does this belong to?\n\n# Pairwise correlation matrix — most-uncorrelated pairs first\nkalshi correlate KXBTCD-... KXETHU-... KXSOL-... --window-days 90\n\n# Build a diversified basket (one HTTP call — universe → cluster cap → corr cap → sizing)\nkalshi basket build --category crypto --min-volume 10000 \\\n  -n 8 --max-per-cluster 2 --max-corr 0.6 \\\n  --bankroll 1000 --kelly 0.25 \\\n  --probs KXBTCD-...:0.62,KXETHU-...:0.58\n\n# \"Find me 5 uncorrelated bets on macro themes\" — one HTTP call\nkalshi basket build --label fed,cpi,fomc,gdp,jobs \\\n  -n 5 --max-per-cluster 1 --max-corr 0.4\n\n# Backtest a basket and read total_return / Sharpe / max DD directly\nkalshi basket backtest --tickers KX-A,KX-B,KX-C --weights 0.4,0.4,0.2 --timeframe 1y\n\n# Kelly-size legs you've already picked\nkalshi basket size --bankroll 1000 --kelly 0.25 --probs KX-A:0.62,KX-B:0.55\n\n# Or let Octagon's model fill in the probabilities for you\nkalshi basket size --auto-probs --tickers KX-A,KX-B,KX-C --bankroll 1000 --kelly 0.25\nkalshi basket size --auto-probs --theme \"AI Race Milestones\" --bankroll 1000 --kelly 0.25\n\n# Diversified basket builder over an explicit candidate pool\nkalshi basket build --tickers KX-A,KX-B,KX-C,KX-D -n 3 --max-per-cluster 1 --max-corr 0.5\nkalshi basket build --theme \"Iran Escalation\" -n 4 --max-per-cluster 1 --max-corr 0.5 --auto-probs --bankroll 1000\n\n# Sanity-check a proposed basket before placing orders (one call, server-side)\nkalshi basket validate --tickers KX-A,KX-B --bankroll 1000 --max-corr 0.5\nkalshi basket validate --theme \"Iran Escalation\" --bankroll 1000\n#   → cluster breakdown, pairwise correlations (top by |corr|), calendar\n#     clashes (weeks where many legs resolve), duplicate underliers, warnings.\n```\n\n### Editorial Theme Dashboard\n\n`themes` is a local registry of editorial narrative buckets (e.g. \"AI Race Milestones\", \"Iran Escalation\") that maps to lists of Kalshi series with optional monthly search-volume annotations. The bot ships with a 25-theme seed dataset in `data/themes_seo.json`. Distinct from Octagon's ML clusters — these are *narratives* you curate.\n\n```bash\n# Seed from the included starter dataset (25 themes, 173 series mappings)\nkalshi themes import\n\n# Browse the registry\nkalshi themes list\nkalshi themes show \"Iran Escalation\"\n\n# THE dashboard view: 25-theme grid with SEO + liquidity\nkalshi themes report\n\n# Flag dead themes (high SEO + zero active Kalshi inventory)\nkalshi themes audit\n#   → Epstein / Celebrity Trials   STALE         4.3M searches, 0 active markets\n#   → RFK Jr Changes Health        NO_INVENTORY  422k searches, 0 active markets\n#   → AI Race Milestones           TRADEABLE     138M searches, 28 active mkts\n#   → Bitcoin Breakout             TRADEABLE     29k searches, 270 active mkts\n\n# Cross-theme dedupe (when a series belongs to multiple themes)\nkalshi themes overlap\n#   → KXUSAIRANAGREEMENT  Iran Escalation · Nuclear Renaissance\n#   → KXMORTGAGERATE      Fed Cuts Aggressively · Housing / Mortgage Crisis\n\n# Build/manage your own themes\nkalshi themes create \"My Macro Hedge\" --label \"...\" --tickers KXRECSSNBER,KXCPIYOY\nkalshi themes add-series \"My Macro Hedge\" KXFEDDECISION,KXU3\nkalshi themes set-search-volume \"My Macro Hedge\" 50000\n\n# Backtest an entire theme as a NAV basket (one top market per series)\nkalshi basket backtest --theme \"Iran Escalation\" --timeframe 3m\nkalshi basket candles --theme \"Fed Cuts Aggressively\" --timeframe 1y --json\n\n# Series-level rollup and NAV\nkalshi series list --min-volume 10000              # liquid series, ranked\nkalshi series KXBTCD --limit 10                    # drill in\nkalshi series candles KXBTCD --timeframe 3m        # series NAV momentum\nkalshi series search bitcoin --limit 10            # keyword → rollup\n\n# Event ↔ outcome ladder\nkalshi events --category Politics --limit 10       # top political events by volume\nkalshi events KXFEDCHAIRNOM-29                     # outcome probabilities + per-contract edge\n\n# Catalyst calendar\nkalshi catalysts upcoming --days 14 --min-volume 5000 --category Politics\n```\n\n### Backtesting\n\nDoes the model find real edge? Look back N days, compare what the model said then to where the market is now.\n\n- **Resolved** — scored against Kalshi settlement (YES=100%, NO=0%)\n- **Unresolved** — mark-to-market vs current Kalshi trading price\n\n**Methodology (matches Supabase reference):**\n- Per-contract `mp`/`kp` come from `outcome_probabilities` on each Octagon snapshot — no event-level fallback.\n- Tradeability gate uses per-contract `volume`/`volume_24h` from the snapshot when present; falls back to Kalshi lifetime volume for pre-API-change cached snapshots.\n- `--min-edge` defaults to 0.5pp so the 0-5% edge bucket stays visible; each signal is tagged with an `edge_bucket` label (`0-5%`, `5-10%`, ..., `90%+`).\n- `flat_bet_roi` is capital-weighted: `sum(pnl) / sum(capital)`, where `capital = kp/100` for YES edges and `(100 - kp)/100` for NO edges.\n\n```bash\nkalshi backtest                              # 15-day lookback (default)\nkalshi backtest --days 30                    # 30-day lookback\nkalshi backtest --max-age 14                 # only score predictions \u003c=14d old\nkalshi backtest --resolved                   # resolved only\nkalshi backtest --unresolved --min-edge 10   # unresolved, 10pp threshold\nkalshi backtest --category crypto            # filter by category\nkalshi backtest --min-volume 10 --min-price 5 --max-price 95   # tradeable contracts only\nkalshi backtest --export results.csv         # per-market detail\n```\n\n```text\nOctagon Backtest — 15-day lookback (04/02 – 04/17)\n══════════════════════════════════════════════════════════\n\n  Events         83\n  Markets        247   (142 resolved, 105 unresolved)\n  Brier (Octagon)   0.168\n  Brier (Market)    0.192\n  Skill Score       +12.5%  [95% CI: +4.1% to +20.8%]\n  Hit rate          61.4%  [95% CI: 54.2% to 68.1%]\n  Flat-bet P\u0026L      +$14.38 (ROI: +7.8%)\n\nRESOLVED (142 markets)\n  Ticker                    Model   Mkt Then   Outcome   Edge    P\u0026L\n  KXBTC-26APR-B95000        72%     58%        YES 100%  +14pp   +$0.42\n  ...\n\nUNRESOLVED (105 markets)\n  Ticker                    Model   Mkt Then   Now       Edge    M2M\n  KXBTC-26MAY-B110000       71%     58%        68%       +13pp   +$0.10\n  ...\n```\n\n### Demo Mode\n\nSet `KALSHI_USE_DEMO=true` in your `.env` to use Kalshi's demo environment. All trades are simulated — no real money at risk.\n\n## Agent Usage\n\nEvery command supports `--json` for structured output, making the bot easy to orchestrate from scripts or AI agents.\n\n```bash\nkalshi search crypto --json\nkalshi similar KXBTC-26APR-B95000 --top-k 10 --json\nkalshi clusters --ranked --timeframe 1y --min-return 0.2 --json\nkalshi correlate KX-A KX-B KX-C --window-days 90 --json\nkalshi basket build --category crypto -n 8 --max-per-cluster 2 --max-corr 0.6 --json\nkalshi analyze KXBTC-26APR-B95000 --json\nkalshi buy KXBTC-26APR-B95000 3 58 --json\nkalshi portfolio --json\n```\n\n### JSON Response Format\n\nAll responses follow the same envelope:\n\n```json\n{\n  \"ok\": true,\n  \"command\": \"analyze\",\n  \"data\": {\n    \"ticker\": \"KXBTC-26APR-B95000\",\n    \"modelProb\": 0.72,\n    \"marketProb\": 0.58,\n    \"edge\": 0.14,\n    \"confidence\": \"very_high\",\n    \"drivers\": [\n      { \"claim\": \"Bitcoin ETF inflows accelerating\", \"impact\": \"high\" }\n    ]\n  },\n  \"meta\": {\n    \"octagon_credits_used\": 3,\n    \"octagon_cache_hits\": 0\n  },\n  \"timestamp\": \"2026-03-30T10:00:00.000Z\"\n}\n```\n\nErrors return `\"ok\": false` with an `error` object containing `code` and `message`. Exit code is 0 for success, 1 for failure.\n\n### Example Orchestration Flow\n\n```bash\n# 1. Find markets\nMARKETS=$(kalshi search crypto --json | jq '.data')\n\n# 2. Analyze top pick\nANALYSIS=$(kalshi analyze KXBTC-26APR-B95000 --json)\nEDGE=$(echo \"$ANALYSIS\" | jq '.data.edge')\n\n# 3. Trade if edge is high enough\nif (( $(echo \"$EDGE \u003e 0.05\" | bc -l) )); then\n  kalshi buy KXBTC-26APR-B95000 3 58 --json\nfi\n\n# 4. Check portfolio\nkalshi portfolio --json\n```\n\n### Server-side basket construction\n\nFor agents that want to skip the per-ticker analysis loop, the `basket build` command pushes universe selection, cluster diversification, correlation gating, and Kelly sizing server-side into a single HTTP call:\n\n```bash\n# Pull Octagon's edge ranking, build a diversified 8-leg crypto basket sized for $1000\nEDGE=$(kalshi search edge --category crypto --min-edge 5 --json | jq '.data.data')\nPROBS=$(echo \"$EDGE\" | jq -r 'map(\"\\(.market_ticker):\\(.model_probability/100)\") | join(\",\")')\n\nkalshi basket build --category crypto --min-volume 10000 \\\n  -n 8 --max-per-cluster 2 --max-corr 0.6 \\\n  --bankroll 1000 --kelly 0.25 --probs \"$PROBS\" --json\n```\n\nThe `watch --theme` command outputs NDJSON (one JSON object per scan cycle), suitable for streaming pipelines.\n\n## Configuration\n\n### Environment Variables\n\nThe setup wizard (run automatically on first launch, or invoke with `kalshi init`) handles this interactively. To edit by hand:\n\n```bash\ncp env.example ~/.kalshi-bot/.env\n```\n\n**Required:**\n\n| Variable | Description |\n|----------|-------------|\n| `KALSHI_API_KEY` | Kalshi API key ID |\n| `KALSHI_PRIVATE_KEY_FILE` | Path to your Kalshi RSA private key PEM file |\n| `OPENAI_API_KEY` | OpenAI API key (default model is GPT-5.4) |\n| `OCTAGON_API_KEY` | Octagon API key. Powers deep research (`analyze`), edge scanning (`search edge`), and the Octagon-backed discovery + basket commands (`search`, `similar`, `clusters`, `peers`, `correlate`, `basket`). Get one at [app.octagonai.co](https://app.octagonai.co) |\n\n**Optional:**\n\n| Variable | Description |\n|----------|-------------|\n| `KALSHI_USE_DEMO` | `true` for demo environment (simulated trades) |\n| `KALSHI_PRIVATE_KEY` | Inline PEM key as alternative to file path |\n| `ANTHROPIC_API_KEY` | Anthropic (Claude) |\n| `GOOGLE_API_KEY` | Google (Gemini) |\n| `XAI_API_KEY` | xAI (Grok) |\n| `OPENROUTER_API_KEY` | OpenRouter (multi-model) |\n| `TAVILY_API_KEY` | Tavily web search for event research |\n\n\u003e **Note:** The bot defaults to GPT-5.4. If using a different provider, switch the model via the `config` command — otherwise queries will fail without `OPENAI_API_KEY`.\n\n### Octagon Credits\n\nEach Octagon report costs 3 credits. Reports are cached with tiered TTLs based on market close proximity — markets closing soon get shorter cache windows. Use `--refresh` to force a fresh report. Set a daily credit ceiling with `config octagon.daily_credit_ceiling \u003cn\u003e`.\n\n### Runtime Settings\n\n```bash\nkalshi config                              # List all settings\nkalshi config risk.kelly_multiplier        # Get a value\nkalshi config risk.kelly_multiplier 0.3    # Set a value\n```\n\n| Setting | Default | Description |\n|---------|---------|-------------|\n| `scan.interval` | `60` | Scan interval in minutes |\n| `scan.theme` | `top50` | Default market theme |\n| `risk.kelly_multiplier` | `0.5` | Kelly fraction (0.5 = half-Kelly) |\n| `risk.max_drawdown` | `0.20` | Max drawdown before circuit breaker |\n| `risk.max_positions` | `10` | Max concurrent open positions |\n| `risk.max_per_category` | `3` | Max positions per event category |\n| `risk.daily_loss_limit` | `200` | Daily loss limit in dollars |\n| `octagon.daily_credit_ceiling` | `100` | Max Octagon credits per day |\n| `alerts.min_edge` | `0.05` | Minimum edge to trigger an alert |\n\n## Architecture\n\n![Kalshi Trading Flow](assets/kalshi-flow-light.png)\n\nThe CLI talks to two external services: the Kalshi exchange API (market data, order placement, portfolio) and the Octagon research API (AI probability estimates, price drivers). Results are cached in a local SQLite database to minimize API calls and credit usage.\n\n### LLM Providers\n\nDefault model is GPT-5.4. Switch with the `config` command.\n\n| Prefix | Provider |\n|--------|----------|\n| `gpt-` | OpenAI |\n| `claude-` | Anthropic |\n| `gemini-` | Google |\n| `grok-` | xAI |\n| `openrouter/` | OpenRouter |\n| `ollama:` | Ollama (local) |\n\n### Development\n\n```bash\nbun dev              # Dev mode with hot reload\nbun run typecheck    # Type checking\nbun test             # Run tests\n```\n\n## Telemetry\n\nThis app collects anonymous usage telemetry to help improve the product.\n**No personal data, API keys, trade details, or natural language inputs are ever collected.**\nOnly command names, tool usage, timing, and success/failure metrics are tracked.\n\nTelemetry is enabled by default. To disable it, add to your `.env`:\n\n```bash\nTELEMETRY_ENABLED=false\n```\n\nOr set the environment variable before running:\n\n```bash\nTELEMETRY_ENABLED=false bunx kalshi-trading-bot-cli@latest\n```\n\n## Documentation\n\nSee the [User Guide](GUIDE.md) for detailed usage instructions, examples, and tips.\n\n## Star History\n\n\u003ca href=\"https://www.star-history.com/?repos=OctagonAI%2Fkalshi-trading-bot-cli\u0026type=date\u0026legend=top-left\"\u003e\n \u003cpicture\u003e\n   \u003csource media=\"(prefers-color-scheme: dark)\" srcset=\"https://api.star-history.com/chart?repos=OctagonAI/kalshi-trading-bot-cli\u0026type=date\u0026theme=dark\u0026legend=top-left\" /\u003e\n   \u003csource media=\"(prefers-color-scheme: light)\" srcset=\"https://api.star-history.com/chart?repos=OctagonAI/kalshi-trading-bot-cli\u0026type=date\u0026legend=top-left\" /\u003e\n   \u003cimg alt=\"Star History Chart\" src=\"https://api.star-history.com/chart?repos=OctagonAI/kalshi-trading-bot-cli\u0026type=date\u0026legend=top-left\" /\u003e\n \u003c/picture\u003e\n\u003c/a\u003e\n\n## License\n\nMIT License — see [LICENSE](LICENSE) for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Foctagonai%2Fkalshi-trading-bot-cli","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Foctagonai%2Fkalshi-trading-bot-cli","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Foctagonai%2Fkalshi-trading-bot-cli/lists"}