openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

feat(integrations): Kalshi trading + market data (#1398, venue 2/3)

Open oxoxDev opened this issue 6 months ago • 2 comments

Summary

  • Adds the Kalshi prediction-market venue (read + write, venue 2/3 of #1398) — public market/event/orderbook reads plus authenticated portfolio + trading actions.
  • Mirrors the Polymarket shape that landed via #2145: dedicated KalshiTool + kalshi_auth (RSA-PSS-SHA256 or HMAC-SHA256), tools_kalshi_execute RPC controller, split readonly + trading catalog entries, GPG-signed micro-commits.
  • 22 unit tests cover the 11 actions (5 read + 6 write), approval gate, credential guard, signature fixtures, 4xx not-retried, 5xx retries-3×, timeout envelope, full-schema deserialization, and HTTPS guard rejection on non-loopback http.

Problem

Issue #1398 asks for trading integrations across Polymarket, Kalshi, and Hyperliquid. Part 1/3 (Polymarket) shipped via #2145. Part 2/3 (Kalshi) is this PR.

Without Kalshi support the agent has no way to surface US-regulated event-contract markets to the user, and the trading skill stays half-built.

Solution

Mirrors the post-merge Polymarket layout (src/openhuman/tools/impl/network/polymarket*):

  1. KalshiTool (src/openhuman/tools/impl/network/kalshi.rs, 779 LOC) — 11-action enum (list_markets, get_market, list_events, get_event, get_orderbook, get_positions, get_balance, get_open_orders, get_fills, place_order, cancel_order). Concurrency-safe on reads; write actions return false from is_concurrency_safe so two place_order calls don't race.
  2. kalshi_auth (src/openhuman/tools/impl/network/kalshi_auth.rs, 236 LOC) — per-request signing via RSA-PSS-SHA256 (dashboard-created bot key) or HMAC-SHA256 (legacy/admin key); timestamp in unix-milliseconds per Kalshi v2 spec; signed message = <ts><method><path> (no body or query). Headers: KALSHI-ACCESS-KEY, KALSHI-ACCESS-TIMESTAMP, KALSHI-ACCESS-SIGNATURE.
  3. Approval gate — write actions return an approval-required error unless arguments.approved = true is passed. Wording matches Polymarket: "Re-invoke with arguments.approved = true after confirming with the user."
  4. HTTPS guard — ensure_https rejects non-loopback http base URLs before signing. Loopback variants (127.0.0.1, [::1], localhost) allowed for local mocks. Mirrors composio.rs carve-out shape.
  5. KalshiConfig (src/openhuman/config/schema/tools.rs) — adds pub kalshi: KalshiConfig to IntegrationsConfig (default enabled = true, base URL https://api.elections.kalshi.com/trade-api/v2, timeout 15s, credentials Optional). KalshiCredentials::is_complete() returns false when api_key/secret are blank.
  6. RPC controller tools_kalshi_execute (src/openhuman/tools/schemas.rs) — mirrors tools_polymarket_execute. Action dispatch routes to the tool; full enum is surfaced in the schema rejection error so callers learn valid action names.
  7. Capability catalog — two entries: skills.kalshi_readonly (metadata) + skills.kalshi_trading (action). Both Beta.
  8. Doc gitbooks/developing/integrations/kalshi.md (+ SUMMARY entry) covering v1 scope, auth setup, action reference, configuration, permissions.

Pitfalls navigated

  • Timestamps: Kalshi auth headers want unix-milliseconds, not seconds. Off-by-1000× silently rejects.
  • yes_price / no_price: cent values (1–99), not dollars. Validated pre-network.
  • client_order_id: auto-generated via Uuid::new_v4() inside the tool when absent; collision avoidance moves out of the caller's hands.
  • expiration_ts: unix-seconds (Kalshi v2 is inconsistent vs the ms timestamp header). Test asserts both shapes.
  • Tickers: keep hyphens + dots intact (INXD-23DEC29-T4500); no encoding tricks.
  • RSA-PSS defaults: explicit SHA-256 + MGF1-SHA256 + salt-length 32. rsa crate defaults differ.

Submission Checklist

  • [x] Tests added or updated (happy path + at least one failure / edge case) per Testing Strategy
  • [x] Diff coverage ≥ 80% — 22 unit tests cover all 11 actions, signature fixtures, approval gate, cred guard, HTTPS guard, error matrix, schema deserialize. Run locally: cargo test --lib kalshi → 22/22 pass.
  • [x] N/A: Coverage matrix updated — Kalshi is a backend-only tool/RPC integration, not surfaced in docs/TEST-COVERAGE-MATRIX.md rows yet (no feature ID exists; would be added when UI lands).
  • [x] N/A: All affected feature IDs from the matrix are listed in the PR description under ## Related — no matrix rows touched.
  • [x] No new external network dependencies introduced (mock backend used per Testing Strategy) — embedded tokio::net::TcpListener mock mirrors Polymarket test rig.
  • [x] N/A: Manual smoke checklist updated if this touches release-cut surfaces (docs/RELEASE-MANUAL-SMOKE.md) — tool/RPC only, no release-cut UI surface.
  • [x] N/A: Linked issue closed via Closes #NNN in the ## Related section — uses Refs #1398 because Hyperliquid (venue 3/3) still pending; #1398 closes only after all 3 venues land.

Impact

  • Runtime: desktop only (Tauri shell hosts core in-process per #1061). No mobile/web surface.
  • Security: bearer-style API key + signature must travel via HTTPS (or loopback for mocks); ensure_https guard blocks credential transmission over plaintext non-loopback.
  • Approval policy: write actions are guarded by require_write_approval — agents must surface confirmation to the user and pass approved = true. Stopgap pattern shared with Polymarket; eventual migration target is #1339 (centralized approval surface).
  • Compatibility: net-new tool registration behind KalshiConfig::enabled (default true). Operators can disable via config. No migration; no removed capability.
  • Performance: 15s default timeout, 3-retry transient policy with exponential backoff matches Polymarket. No event-bus subscribers added.

Related

  • Refs #1398 (Kalshi full — venue 2/3)
  • Follow-up PR(s)/TODOs:
    • Polymarket parity: add cancel_order happy-path + explicit signed_reads_require_credentials tests (Polymarket already had write paths but the regression net is thinner than Kalshi's)
    • Hyperliquid (venue 3/3) — opens after Kalshi merges; bakes in the 8 lessons captured in temp/kalshi-poly-test-plan.md §7
    • f64 → rust_decimal::Decimal migration for financial amounts (deferred from M3gA-Mind PR #2145 review)
    • SecretStore migration once #1900 lands

AI Authored PR Metadata (required for Codex/Linear PRs)

Linear Issue

  • Key: N/A
  • URL: N/A

Commit & Branch

  • Branch: feat/1398-kalshi
  • Commit SHA: e68fa585 (tip; 13 commits total off upstream/main @ 65d92bf1)

Validation Run

  • [x] pnpm --filter openhuman-app format:check — N/A: no TypeScript / app changes in this PR; pure Rust + docs + fixtures.
  • [x] pnpm typecheck — N/A: same reason as above.
  • [x] Focused tests: cargo test --lib kalshi → 22 passed, 0 failed in 1.03s.
  • [x] Rust fmt/check (if changed): cargo fmt --check --all clean; cargo check --workspace clean (pre-existing warns in slack_backfill.rs unrelated).
  • [x] Tauri fmt/check (if changed): N/A — Tauri shell untouched.

Validation Blocked

  • command: cargo clippy --lib -- -D warnings
  • error: 119 pre-existing clippy errors on upstream/main in inference/local/mod.rs, webview_apis/client.rs, webview_notifications/types.rs, desktop_companion/*_tests.rs, slack_backfill.rs, etc.
  • impact: kalshi-scoped clippy gate is clean (0 hits after the match_like_matches_macrofix in commitab4131ca); the remaining 119 errors are unrelated to this PR. Same blocker documented on #2116.

Behavior Changes

  • Intended behavior change: net-new kalshi tool + RPC controller; no existing behavior altered. Polymarket tool, registry, and RPC controller untouched.
  • User-visible effect: when integrations.kalshi.enabled = true (default) and creds are configured, the agent can call Kalshi to list markets/events/orderbooks (read) and (with explicit user approval) place/cancel orders.

Parity Contract

  • Legacy behavior preserved: Polymarket path unaffected; tools registry simply gains a second venue.
  • Guard/fallback/dispatch parity checks: HTTPS loopback carve-out matches composio.rs shape; approval-gate wording matches Polymarket; is_concurrency_safe returns false for place_order + cancel_order same as Polymarket post-PR-#2145; 3-attempt retry on 5xx matches Polymarket MAX_RETRY_ATTEMPTS = 3.

Local smoke (2026-05-20)

Booted openhuman-core on a temp workspace + hit openhuman.tools_kalshi_execute via JSON-RPC:

  • T1 — place_order without approved=true → returns the approval-required error before any network egress.
  • T2 — get_positions with approved=true but no creds → returns "Kalshi credentials are required for this action".
  • T3 — action: "not_a_real_action" → schema rejection with full 11-action enum surfaced.
  • T4 — list_markets against real Kalshi API → geo-blocked from local IP; timeout error envelope returned as expected ("Kalshi request timed out after 15s: GET /markets"). CI on GH-US will exercise the real-network path.

Test plan covering Polymarket + Kalshi parity (and the 8 lessons to bake into Hyperliquid) lives at temp/kalshi-poly-test-plan.md.

Summary by CodeRabbit

Release Notes

  • New Features

    • Kalshi trading platform integration now available for market browsing, portfolio management, and order placement/cancellation.
  • Documentation

    • Added Kalshi integration guide with configuration, authentication, and API specifications.

Review Change Stack

oxoxDev avatar May 20 '26 10:05 oxoxDev

📝 Walkthrough

Walkthrough

This PR adds a complete Kalshi trading integration to OpenHuman, including RSA/HMAC request authentication, a Tool implementation with endpoint dispatch and HTTP retry logic, comprehensive async tests with a mock HTTP server, RPC controller registration, capability catalog entries, and configuration schema types.

Changes

Kalshi Trading Integration

Layer / File(s) Summary
Configuration schema and dependency
Cargo.toml, src/openhuman/config/schema/tools.rs
Added rsa crate (v0.9, features: pem, sha2). Introduced KalshiCredentials (with is_complete() validation and redacted Debug) and KalshiConfig (base URL, timeout, optional credentials) with defaults and integration into IntegrationsConfig.
Request authentication and signing
src/openhuman/tools/impl/network/kalshi_auth.rs
RSA-PSS and HMAC-SHA256 signing module. Produces authenticated request headers (access key, Unix-milliseconds timestamp, base64 signature). Supports dual-mode signing: RSA-PSS when private key PEM is set, HMAC-SHA256 when only secret is provided. Includes unit tests for both modes and error cases.
Core tool implementation and endpoint dispatch
src/openhuman/tools/impl/network/kalshi.rs
KalshiTool struct with configured reqwest client and KalshiRequest enum covering 11 operations (6 reads: markets, events, orderbook, positions, balance, orders, fills; 2 writes: place_order, cancel_order; plus cancel and get single items). handle_request dispatcher routes read operations via unsigned GET and write operations via signed POST/DELETE. send_with_retry unifies HTTP calls with timeout/retry/backoff, deserializes JSON responses (empty → null), and truncates error bodies. Input validation ensures ticker non-empty, prices in 1–99 cents (YES/NO), count > 0, and UUID-form client_order_id. Tool trait implementation provides action schema, marks write actions as non-concurrent, enforces SecurityPolicy rate limits and budget, and requires approved=true for writes.
Tool test suite
src/openhuman/tools/impl/network/kalshi_tests.rs
Mock TCP HTTP server (request parsing via Content-Length, response fixture queuing/serving, optional delays). Tests cover: happy-path market/event/orderbook listings and single-item lookups; authenticated reads (positions, balance, open orders, fills) with signature header validation; approval-gated place_order and cancel_order (no HTTP on unapproved, signed POST/DELETE on approved); error handling (4xx no-retry, 5xx retry ×3, timeout on delay); schema validation and deserialization; security guards (credentials required for signed reads, HTTPS+loopback allowlisting for auth).
System integration and RPC wiring
src/openhuman/tools/impl/network/mod.rs, src/openhuman/tools/ops.rs, src/openhuman/tools/schemas.rs, src/openhuman/about_app/catalog.rs
Module registration: mod kalshi; pub use kalshi::KalshiTool;. Tool registration in all_tools_with_runtime (enabled flag check, debug logging). RPC schema tools_kalshi_execute with action/optional arguments inputs and data output. Handler handle_kalshi_execute loads config, constructs tool with default security policy, validates arguments, injects action, executes, returns result payload. Capability catalog: two CapabilityPrivacy constants (market data and trading data, each marking Kalshi API as external destination) and two skill capabilities (readonly browse, trading + order placement/cancellation) wired to privacy metadata and the kalshi tool with approved=true requirement for writes.
Documentation and fixtures
gitbooks/SUMMARY.md, gitbooks/developing/integrations/kalshi.md, src/openhuman/config/mod.rs, src/openhuman/config/schema/mod.rs, tests/fixtures/kalshi/*
Gitbook documentation: API base URL, endpoint categories (public/authenticated reads, writes), authentication (api key, RSA-PSS private key, HMAC secret), required headers (access key, timestamp, signature), validation (approved gating, UUID client_order_id, price cents 1–99), config structure (integrations.kalshi). Re-export list formatting updates. 13 JSON fixtures: market/event listings and single-item, orderbook sides, positions/balance/orders/fills snapshots, place_order/cancel_order responses, client/server error payloads.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

  • tinyhumansai/openhuman#1398 — This PR implements the Kalshi portion of the trading integrations umbrella, directly addressing the request to add a Kalshi integration with read and trading capabilities.

Suggested labels

feature

Suggested reviewers

  • graycyrus

Poem

🐰 A rabbit hops through trading API,
RSA keys and HMAC spree,
Signed headers dancing in the air,
Kalshi markets, everywhere!
Mock servers mock, tests pass with care,
New trades unfold—a feature fair! 📈

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.43% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly and specifically describes the main change: adding Kalshi integration (both trading and market data capabilities) as part of a multi-venue integration effort. It is concise, uses the conventional 'feat(integrations):' prefix, and directly summarizes the primary deliverable of the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 20 '26 10:05 coderabbitai[bot]

@oxoxDev as discussed; mark it as ready to review once you start working on this

graycyrus avatar May 22 '26 08:05 graycyrus

I'd highly recommend we make this as a skill/mcp connector etc...

senamakel avatar May 23 '26 00:05 senamakel