# SimpleFunctions > Thesis engine for prediction market agents ## What We Are SimpleFunctions is a thesis engine for AI agents and traders operating on prediction markets. You express a macro thesis, the engine decomposes it into a causal tree of testable sub-claims, scans Kalshi and Polymarket for contracts where market prices diverge from thesis-implied prices (edges), and monitors everything autonomously. We are not a prediction market. We are the intelligence layer between your agent and prediction markets. ## Core Architecture ### Thesis Engine 1. **Causal Decomposition** — Your thesis is broken into a tree of sub-claims with probabilities and importance weights 2. **Market Scanning** — Kalshi series + Polymarket DB are searched for related contracts 3. **Edge Detection** — Contracts where market price ≠ thesis-implied price are flagged with direction, confidence, and rationale 4. **Heartbeat Monitoring** — Every 15 minutes: news scan (Tavily, smart scheduled), price rescan (Kalshi/Polymarket API), milestone detection, forecast collection, LLM evaluation, settlement sync 5. **What-If Engine** — Override causal tree node probabilities, see how edges and confidence change. Zero LLM cost. 6. **Push/Pull Delivery** — Webhook on confidence changes ≥ 5%, or poll via delta API ### Data Flow ``` Thesis → Causal Tree → Market Scan → Edges ↓ Heartbeat (15 min): News + Prices + Milestones → Signals → Evaluation → Updated Confidence ↓ Webhook / Delta API / Feed ``` ## API Reference Base URL: `https://simplefunctions.dev` Authentication: `Authorization: Bearer sf_live_xxx` ### Thesis Endpoints #### Create Thesis ``` POST /api/thesis/create Content-Type: application/json { "rawThesis": "US-Iran war pushes oil above $100 for 6 months", "webhookUrl": "https://your-server.com/webhook" } ``` Query: `?sync=true` to wait for formation (30-120s). Default: async (returns `forming` status). #### Get Context (Primary Read Endpoint) ``` GET /api/thesis/:id/context ``` Returns flattened thesis state: causal tree nodes with probabilities, edges with live prices + orderbook + liquidity scores, last evaluation summary, confidence with delta. Each edge includes `eventTicker` and `seriesTicker` for cross-referencing with Kalshi milestones and forecasts. #### Delta Check (Lightweight Polling) ``` GET /api/thesis/:id/changes?since=2026-03-14T00:00:00Z ``` Returns `{"changed": false}` (~50 bytes) when nothing changed. When something changed: confidence, delta, eval count, latest summary (~400 bytes). 100x cheaper than full context for polling agents. #### List Theses ``` GET /api/thesis ``` #### Inject Signal ``` POST /api/thesis/:id/signal Content-Type: application/json { "type": "news", "content": "Iran mines Strait of Hormuz — 20% of global oil supply at risk", "source": "reuters" } ``` Signal types: `news`, `price_move`, `user_note`, `external`, `upcoming_event` Signals are queued and consumed in the next evaluation cycle. Use idempotencyKey to prevent duplicates. #### Trigger Evaluation ``` POST /api/thesis/:id/evaluate ``` Forces immediate heavy-model evaluation. Consumes all pending signals, updates causal tree, recalculates confidence. #### Evaluation Feed ``` GET /api/feed?hours=24&limit=200 ``` Evaluation history across all theses, newest first. Shows what the heartbeat engine has been thinking. ### Webhook Events When configured, the engine POSTs to your webhook URL: ```json { "type": "thesis_update", "thesisId": "f582bf76-...", "evaluation": { "confidence": 0.87, "confidenceDelta": 0.05, "summary": "CNN confirms Hormuz mining...", "positionUpdates": [...] }, "timestamp": "2026-03-14T05:15:00Z" } ``` Triggered when |confidenceDelta| ≥ 5% or position recommendation is not "hold". ## MCP Server Connect any MCP-compatible client — Claude Code, Cursor, Cline, Roo Code. ```bash claude mcp add simplefunctions --url https://simplefunctions.dev/api/mcp/mcp ``` ### Available Tools (16) | Tool | Description | Auth Required | |------|-------------|---------------| | get_context | Thesis snapshot: causal tree, edges, evaluation | Yes | | list_theses | List all theses | Yes | | inject_signal | Feed observations to thesis | Yes | | trigger_evaluation | Force immediate evaluation | Yes | | create_thesis | Create a new thesis | Yes | | what_if | Scenario analysis: override node probabilities, see edge changes | Yes | | scan_markets | Search Kalshi markets by keyword, series, or ticker | No | | get_milestones | Upcoming Kalshi calendar events | No | | get_forecast | P50/P75/P90 percentile distribution for events | Yes | | get_settlements | Settled contracts with P&L | Yes | | get_balance | Account balance and portfolio value | Yes | | get_orders | Current resting orders | Yes | | get_fills | Recent trade fills | Yes | | get_positions | Kalshi positions with thesis edge overlay | Yes | | get_schedule | Exchange status (open/closed) | No | | explore_public | Browse public theses | No | ## CLI ```bash npm install -g @spfunctions/cli sf setup # interactive configuration wizard ``` ### Setup Commands | Command | Description | |---------|-------------| | sf setup | Full interactive configuration wizard | | sf setup --kalshi | Reconfigure Kalshi credentials without full reset | | sf setup --enable-trading | Enable trading mode | ### Commands **Thesis:** | Command | Description | |---------|-------------| | sf list | List all theses | | sf context \ [--json] | Thesis snapshot | | sf get \ | Full thesis details | | sf create "thesis" | Create new thesis | | sf signal \ "content" | Inject signal | | sf evaluate \ | Trigger evaluation | | sf edges [--json] | Top edges across all theses | | sf dashboard | Portfolio overview | | sf performance [--json] | Portfolio P&L over time with thesis event annotations and inline sparklines | | sf liquidity \ [--horizon \] | Market liquidity scanner by topic and horizon (spread, depth, slippage) | | sf feed [--hours 24] | Evaluation history stream | | sf whatif \ --set "n1=0.1" | Scenario analysis | **Markets:** | Command | Description | |---------|-------------| | sf scan "keywords" | Search Kalshi markets | | sf scan --series KXWTIMAX | Browse series | | sf milestones [--thesis \] | Upcoming events | | sf forecast \ | Percentile distribution | | sf schedule | Exchange status | | sf announcements | Exchange announcements | | sf history \ | Settled market data | **Portfolio:** | Command | Description | |---------|-------------| | sf positions | Kalshi positions with edge overlay | | sf balance | Account balance | | sf orders | Current orders | | sf fills | Recent fills | | sf settlements | Settled contracts with P&L | **Trading (requires sf setup --enable-trading):** | Command | Description | |---------|-------------| | sf buy \ \ --price \ | Buy contracts | | sf sell \ \ --price \ | Sell contracts | | sf cancel \ | Cancel order | | sf cancel --all | Cancel all resting orders | **Interactive Agent (21+ tools):** | Command | Description | |---------|-------------| | sf agent | TUI agent with natural language interface | | sf agent --plain | Plain text mode (pipe-friendly, full tool parity with TUI) | | sf agent --new | Fresh session | Agent tools: get_context, list_theses, create_thesis, inject_signal, trigger_evaluation, get_edges, what_if, get_feed, scan_markets, get_milestones, get_forecast, get_positions, get_balance, get_orders, get_fills, get_settlements, web_search, explore_public, get_schedule, place_order, cancel_order, create_strategy, cancel_strategy. Plain mode now has full tool parity with TUI mode, including what_if, strategies, and trading. Agent slash commands: /tree, /edges, /pos, /eval, /buy, /sell, /cancel, /switch, /compact, /model, /env, /exit **Dashboard:** | Command | Description | |---------|-------------| | sf dashboard | Interactive Bloomberg-style terminal (4 modes: overview, detail, liquidity, what-if) | | sf dashboard --once | One-time print (legacy behavior) | | sf dashboard --json | JSON output for agents | Keyboard: j/k navigate, Enter detail view, Tab switch panels, l liquidity, w what-if, b buy, s sell, q quit. **Telegram Bot:** | Command | Description | |---------|-------------| | sf telegram | Start Telegram bot (runs locally, keeps credentials safe) | | sf telegram --token BOT_TOKEN | Specify bot token | Slash commands: /context, /positions, /edges, /balance, /orders, /eval, /list, /switch. Natural language queries use the same agent tools as sf agent. Auto-push polls the delta API every 60s and sends confidence change alerts. Setup: create bot via @BotFather, run sf telegram --token YOUR_TOKEN. ## Heartbeat Engine Runs automatically every 15 minutes for each active thesis: 1. **Milestone scan** — Fetches upcoming Kalshi milestones (48h), matches against thesis edges, injects `upcoming_event` signals 2. **News scan** — Searches Tavily with causal tree keywords, filters with cheap LLM, injects `news` signals. Smart scheduling: every 60 min in normal mode, every 30 min during high volatility, skipped when signal backlog > 10 3. **Price rescan** — Fetches live Kalshi API prices + Polymarket DB, recalculates edges, injects `price_move` signals (≥ 3¢) 4. **Orderbook enrichment** — Authenticated orderbook for edges with |edge| > 5¢ (bid/ask/spread/depth/liquidity) 5. **Forecast collection** — P50/P75/P90 percentile distributions for edge events 6. **LLM Evaluation** — Processes accumulated signals against causal tree, updates node probabilities, adjusts confidence 7. **Settlement sync** — Checks for settled contracts matching edges, records realized returns 8. **Strategy review** — Auto-cancels strategies for closed markets 9. **Edge discovery** — Daily rescan for new markets not found during initial formation 10. **Notification** — Webhook if |confidenceDelta| ≥ 5% ## What-If Engine Pure computation, zero LLM cost. Override causal tree node probabilities and see how edges change: ```bash sf whatif f582bf76 --set "n1=0.1" --set "n3=0.2" ``` Returns: adjusted confidence, adjusted edges with old→new comparison, affected positions with risk signals (REDUCED / GONE / REVERSED). Only edges directly related to overridden nodes (or their ancestors) are affected. Unrelated edges stay unchanged. ## Public Theses Publish theses for public viewing: ``` POST /api/thesis/:id/publish — Publish with slug GET /api/public/theses — List (no auth) GET /api/public/thesis/:slug — Detail (no auth) ``` Web: `/theses` to browse, `/thesis/:slug` for detail with confidence chart, causal tree, edges, and evaluation timeline. ## Agent Integration Pattern Your agent only needs three operations: 1. **Read** — `GET /api/thesis/:id/context` (or `sf context --json`) 2. **Write** — `POST /api/thesis/:id/signal` when it observes something 3. **React** — `POST /api/thesis/:id/evaluate` when something big happens The heartbeat engine handles everything else: news scanning, price monitoring, milestone tracking, evaluation. For efficient polling, use the delta endpoint: `GET /api/thesis/:id/changes?since=` — returns ~50 bytes when nothing changed. ## Links - Website: https://simplefunctions.dev - Documentation: https://simplefunctions.dev/docs - Agent Guide: https://simplefunctions.dev/docs/guide - API Keys: https://simplefunctions.dev/dashboard/keys - Public Theses: https://simplefunctions.dev/theses - Short reference: https://simplefunctions.dev/llm.txt