API Reference

Base URL: https://simplefunctions.dev

All endpoints require authentication via API key in the Authorization header.


Authentication

Include your API key in every request:

curl -H "Authorization: Bearer sf_live_xxx" \
  https://simplefunctions.dev/api/thesis

Get your API key from the Dashboard.


Thesis

Create Thesis

POST /api/thesis/create

Creates a new thesis and starts the formation process. The system decomposes your thesis into a causal tree, scans Kalshi + Polymarket for related contracts, and identifies mispriced edges.

Request:

{
  "rawThesis": "US-Iran war will not end quickly",
  "webhookUrl": "https://your-server.com/webhook"
}
FieldTypeRequiredDescription
rawThesisstringYesYour thesis statement
webhookUrlstringNoURL for webhook notifications

Query Parameters:

ParamDescription
sync=trueWait for formation to complete (up to 5 min). Default is async.

Response (sync, 200):

{
  "id": "f582bf76-...",
  "status": "active",
  "confidence": "0.505",
  "causalTree": { "rootClaim": "...", "nodes": [...] },
  "edgeAnalysis": {
    "edges": [
      {
        "marketId": "KXRECSSNBER-26",
        "marketTitle": "Will there be a recession in 2026?",
        "venue": "kalshi",
        "direction": "yes",
        "marketPrice": 30,
        "thesisImpliedPrice": 55,
        "edgeSize": 25,
        "eventTicker": "KXRECSSNBER-26",
        "seriesTicker": "KXRECSSNBER"
      }
    ],
    "totalMarketsAnalyzed": 154
  }
}

Get Context

GET /api/thesis/:id/context

Returns a flattened snapshot optimized for agents and CLI. Primary read endpoint.

Response includes:

{
  "thesisId": "f582bf76-...",
  "thesis": "Trump cannot exit the Iran war...",
  "status": "active",
  "confidence": 0.82,
  "causalTree": { "rootClaim": "...", "nodes": [...] },
  "edges": [
    {
      "marketId": "KXRECSSNBER-26",
      "market": "Will there be a recession in 2026?",
      "venue": "kalshi",
      "direction": "yes",
      "marketPrice": 34,
      "thesisPrice": 55,
      "edge": 21,
      "eventTicker": "KXRECSSNBER-26",
      "seriesTicker": "KXRECSSNBER",
      "orderbook": {
        "bidPrice": 33, "askPrice": 35, "spread": 2,
        "bidDepth": 814, "askDepth": 500, "liquidityScore": "high"
      },
      "executableEdge": 20
    }
  ],
  "lastEvaluation": {
    "summary": "...",
    "confidenceDelta": 0.10,
    "previousConfidence": 0.72,
    "newConfidence": 0.82
  }
}

Each edge includes eventTicker and seriesTicker for cross-referencing with Kalshi milestones and forecasts.

Other Thesis Endpoints

MethodEndpointDescription
GET /api/thesisList all theses
GET /api/thesis/:idFull thesis state (raw)
PATCH /api/thesis/:idUpdate status, webhookUrl, metadata

Signals

Inject Signal

POST /api/thesis/:id/signal

{
  "type": "news",
  "content": "FBI warns California drone threat related to Iranian proxies",
  "source": "reuters"
}

Signal types:

TypeDescription
newsNews article — auto-injected by heartbeat, or manual
price_moveMarket price change ≥ 3¢ — auto-injected by heartbeat
user_noteManual note from user or agent
externalExternal system signal
upcoming_eventKalshi milestone event — auto-injected by heartbeat when matching edges

Signals are queued and consumed in the next evaluation cycle (every 15 min).


Evaluation

Trigger Evaluation

POST /api/thesis/:id/evaluate

Triggers an immediate evaluation cycle using the heavy model (Claude Opus). Consumes all pending signals, updates causal tree, recalculates confidence.


Webhooks

When a webhook URL is configured, we POST events on confidence changes (≥ 5%) and non-hold position recommendations.


Heartbeat Engine

The backend runs an automatic cycle every 15 minutes for each active thesis:

  1. Milestone scan — Fetches upcoming Kalshi milestones (48h window), matches against thesis edge tickers, injects as upcoming_event signals
  2. News scan — Searches Tavily for relevant news, filters with cheap LLM, injects as news signals
  3. Price rescan — Fetches live prices from Kalshi API + Polymarket DB, recalculates edge sizes, injects ≥ 3¢ changes as price_move signals
  4. Orderbook enrichment — Fetches authenticated orderbook data for edges with |edge| > 5¢
  5. Forecast collection — Fetches P50/P75/P90 percentile distributions for edge events (where available)
  6. Evaluation — LLM evaluates accumulated signals against causal tree, updates node probabilities and confidence
  7. Settlement sync — Checks for settled contracts matching thesis edges, records realized returns
  8. Strategy review — Checks active strategies against updated edges, auto-cancels if market closed
  9. Notification — Sends webhook if |confidenceDelta| ≥ 5%

No user action needed. The engine runs automatically once a thesis is active.


CLI

Setup

npm install -g @spfunctions/cli
sf setup

The wizard configures API keys (SF, OpenRouter, Kalshi, Tavily) with real-time validation. Optionally enables trading. Config saved to ~/.sf/config.json.

Config priority: env vars > config file > defaults.

Thesis Commands

CommandDescription
sf listList all theses
sf get <id>Full thesis details
sf context <id> [--json]Thesis snapshot (primary agent endpoint)
sf create "thesis text"Create new thesis (sync by default)
sf signal <id> "content"Inject a signal
sf evaluate <id>Trigger deep evaluation
sf edges [--json]Top edges across all theses
sf dashboard [--json]Portfolio overview — risk, edges, P&L

Market Discovery

CommandDescription
sf scan "keywords"Search Kalshi markets (no auth)
sf scan --series KXWTIMAXBrowse series events + live prices
sf scan --market KXWTIMAX-26DEC31-T135Single market detail
sf milestones [--hours 72] [--thesis <id>]Upcoming Kalshi calendar events
sf forecast <eventTicker> [--days 7]P50/P75/P90 percentile distribution
sf history <ticker>Historical data for settled markets
sf announcementsExchange announcements
sf scheduleExchange status (open/closed)

Portfolio & Trading

CommandDescription
sf positionsKalshi positions with thesis edge overlay
sf balanceAccount balance + portfolio value
sf orders [--status resting]Current orders
sf fills [--ticker X]Recent trade fills
sf settlements [--thesis <id>]Settled contracts with P&L

Trading (requires sf setup --enable-trading)

CommandDescription
sf buy <ticker> <qty> --price <cents>Buy contracts (limit order)
sf buy <ticker> <qty> --marketBuy contracts (market order)
sf sell <ticker> <qty> --price <cents>Sell contracts
sf cancel <orderId>Cancel a single order
sf cancel --all [--ticker <prefix>]Cancel all resting orders
sf rfq <ticker> <qty>Request for quote (large orders)

All trading commands have a 3-second countdown before execution. Use --yes-i-am-sure to skip.

Publishing

CommandDescription
sf publish <id> --slug <slug>Publish thesis for public viewing
sf unpublish <id>Remove from public
sf explore [slug]Browse public theses (no auth)

Interactive Agent

sf agent launches an interactive terminal session with natural language access to all features.

sf agent                    # continue last session
sf agent f582bf76 --new     # fresh session for specific thesis
sf agent --plain            # plain text mode (no TUI, works in pipes)

Agent Tools

The agent has 15+ tools it calls automatically:

CategoryTools
Thesisget_context, list_theses, inject_signal, trigger_evaluation
Marketsscan_markets, get_milestones, get_forecast
Portfolioget_positions, get_balance, get_orders, get_fills, get_settlements
Researchweb_search, explore_public
Infoget_schedule
Tradingplace_order, cancel_order (only when trading enabled)

Trading tools show an order preview and ask for confirmation before executing.

Slash Commands

CommandDescription
/treeDisplay causal tree
/edgesEdge list with orderbook data
/posPositions with P&L
/evalTrigger evaluation
/buy TICKER QTY PRICEQuick buy (trading enabled only)
/sell TICKER QTY PRICEQuick sell
/cancel ORDER_IDCancel order
/switch <id>Switch thesis
/compactCompress conversation history
/model <name>Switch model
/envShow config status
/exitSave and exit

Sessions persist at ~/.sf/sessions/. Use --new to start fresh.


MCP Server

Connect any MCP-compatible client — Claude Code, Cursor, Cline, Roo Code.

claude mcp add simplefunctions --url https://simplefunctions.dev/api/mcp/mcp

Tools: get_context, list_theses, inject_signal, trigger_evaluation, scan_markets, create_thesis, explore_public, get_milestones, get_forecast, get_settlements, get_balance, get_orders, get_fills, get_schedule.

scan_markets, explore_public, get_milestones, and get_schedule work without an API key.


Agent Integration

For AI agents (Claude Code, Cursor, custom):

  1. Install: npm install -g @spfunctions/cli
  2. Configure: sf setup
  3. Read: sf context <id> --json — thesis state with edges, orderbook, evaluation
  4. Write: sf signal <id> "content" — inject observations
  5. Evaluate: sf evaluate <id> — force deep analysis

The heartbeat engine handles news scanning, price refreshing, milestone tracking, and evaluation automatically every 15 minutes. Agents only need to read context and inject observations.


Public Theses

Publish a thesis for public viewing. No auth required to read.

MethodEndpointDescription
POST /api/thesis/:id/publishPublish with slug + description
DELETE /api/thesis/:id/publishUnpublish
GET /api/public/thesesList all public theses
GET /api/public/thesis/:slugFull public thesis data

Web: /theses to browse, /thesis/:slug for detail view with confidence chart, causal tree, edges, and evaluation timeline.