Documentation
SimpleFunctions is the runtime for prediction markets — perception, cognition, and execution in one stack. Pick an entrypoint below or scroll for the full one-page reference.
Start here
Curl one endpoint, install the CLI, talk to the agent. Two minutes from zero.
Thesis → causal tree → edge detection → 24/7 monitoring loop. The pipeline.
Walked-through examples: build a thesis, find an edge, route an intent.
What we built, who it is for, and why no exchange will ship it.
Integration
One-line install for Claude Code, Cursor, Cline. 54 tools, public ones unauthed.
50+ commands. sf scan, sf agent, sf intent, sf runtime, sf telegram. JSON on every call.
90+ endpoints. /api/agent/world, /api/public/screen, /api/public/yield-curves, more.
Sub-second WebSocket + REST feed at data.simplefunctions.dev/v1/. Orderbook, trades, candles, heat-ranked featured.
Multi-daemon architecture, smart-mode LLM gating, crash recovery, cost breakdown.
Autonomous portfolio management. Views, strategies, risk gates, rolling context.
Deep dives
The single-page reference your LLM should ingest. Tools, commands, response shapes.
IY, CRI, EE, RV, VR, IAR, Adj IY, Residual VR, LAS, CVR, PIV, OR — the indicator vocabulary, defined precisely.
The /api/agent/world endpoint and the spec underneath it (ai-world-state).
HuggingFace dataset releases, snapshot cadence, and resolution provenance.
Full one-page reference
Overview
SimpleFunctions is prediction market data, indicators, and autonomous trading infrastructure. Structured, decision-ready data from Kalshi, Polymarket, X/Twitter, and traditional markets — monitored 24/7. CLI, MCP server, REST API, and interactive agent with cognitive guardrails.
Quick Start
0. No install needed — try it now
curl https://simplefunctions.dev/api # live data in your terminal
curl https://simplefunctions.dev/api/changes # recent market changes
curl https://simplefunctions.dev/api/tools # full capability manifest
1. Install the CLI
npm install -g @spfunctions/cli
sf scan "gold" # search Kalshi + Polymarket (no auth)
sf query "iran oil" # LLM-enhanced search — markets + X + answer
sf watch "gold" # server-side change detection feed
sf agent # interactive agent (all tools + skills)
All commands work without an API key. Explorer mode gives you full market access.
2. Explore — ask questions (no thesis needed)
sf agent # opens in explorer mode — all tools, no setup
Ask anything: "what's happening with Iran?", "show me gold contracts", "any new markets today?". The agent has full access to scan, query, watch, and explore — no thesis required. When you form a view, say it: "I think oil stays above $100" — the agent creates a thesis automatically.
3. Create a thesis (optional — makes context richer)
sf setup # API key + optional Kalshi/Polymarket credentials (2 min)
sf thesis create 'US-Iran war will not end quickly. Oil stays above $100 through Q2 2026.'
Pass a testable claim — a statement that can be true or false at a future date. Use single quotes (not double) so $100 isn't swallowed by your shell. Takes ~60s; system builds a causal tree, scans Kalshi + Polymarket for related contracts, identifies edges, and starts 24/7 monitoring.
4. Focused context
sf thesis context <id> # thesis-specific: causal tree, edges, evaluation, track record
sf edges # top mispriced contracts across all theses
sf dashboard # interactive Bloomberg-style terminal
That's it. The system runs 24/7. See the Agent Guide for full integration reference.
How It Works
Thesis → Causal Tree
Your plain-text thesis is decomposed into a tree of verifiable assumptions. Each node has a probability (0-1) and importance weight. The overall confidence is the weighted product.
Thesis: "Oil stays above $100 for 6 months"
├── n1: OPEC maintains production cuts (0.70, weight 0.30)
│ ├── n1.1: Saudi compliance remains high (0.80)
│ └── n1.2: Russia doesn't break quota (0.60)
├── n2: Demand stays strong (0.65, weight 0.25)
├── n3: Geopolitical risk premium persists (0.75, weight 0.25)
└── n4: No US SPR release (0.80, weight 0.20)
Confidence: 72%
Edge Detection
The system maps causal nodes to prediction market contracts and compares:
- Market price: what Kalshi/Polymarket traders think (e.g. 34 cents)
- Thesis price: what your causal model implies (e.g. 55 cents)
- Edge: the difference (21 cents)
- Executable edge: edge minus half the spread (real edge after crossing)
24/7 Monitoring
Every 15 minutes, the heartbeat engine:
- Scans news (3 queries including one adversarial — never filters out contradictory evidence)
- Refreshes prices from Kalshi API + Polymarket CLOB
- Enriches orderbooks (bid/ask depth for edges > 5 cents)
- Evaluates signals against causal tree (checks kill conditions first)
- Computes track record (hit rate: % of edges that moved toward thesis)
- Discovers new edges (daily) and augments the causal tree with new nodes (weekly)
Integration Options
MCP Server
One-line setup for Claude Code, Cursor, Cline, or Roo Code:
claude mcp add simplefunctions --url https://simplefunctions.dev/api/mcp/mcp
54 tools available. Public tools work without auth. See the Agent Guide for the full list.
CLI
Every command supports --json. Key commands support --share for shareable URLs.
Explore (no auth):
| Command | What it does |
|---|---|
sf scan "gold" | Search Kalshi + Polymarket |
sf scan "btc" --expires-before 24h --price-min 3 --price-max 9 | Scan with server-side filters (expiry / price / volume) |
sf overround "senate majority leader" | Sum YES asks across multi-leg event; flag arb |
sf newmarkets --hours 24 | Newly listed markets (catch fresh contracts before pro MM) |
sf query "iran oil" | LLM-enhanced search (markets + X + answer) |
sf watch "gold" | Price change detection feed |
sf watch "gold" orderbook | Live bid/ask/spread/depth tracking |
sf watch "gold" flow | Momentum detection, volume spikes |
sf watch "gold" cross-venue | Kalshi vs Polymarket spread tracking |
sf agent | Interactive agent (all tools + skills, explorer mode) |
sf context | Global market snapshot |
sf markets | Traditional markets (SPY, VIX, GLD, TLT, USO) |
sf explore | Browse public theses |
sf status | Health check: API, auth, Kalshi, Polymarket, theses |
sf dashboard | Interactive Bloomberg-style terminal |
Thesis + analysis:
| Command | What it does |
|---|---|
sf thesis create "thesis" | Create thesis with causal tree + edges |
sf thesis context <id> | Thesis-specific snapshot |
sf edges | Top mispriced contracts across all theses |
sf whatif <id> --set "n1=0.1" | Scenario analysis (zero LLM cost) |
sf thesis signal <id> "text" | Inject observation |
sf thesis evaluate <id> | Force deep evaluation |
sf feed | Evaluation history |
sf contagion | Markets that should have moved but didn't |
sf cross-venue | Kalshi vs Polymarket price comparison |
sf calibration | Brier scores + calibration metrics |
sf regime [ticker] | Market regime analysis (--history) |
Knowledge + community:
| Command | What it does |
|---|---|
sf concepts [slug] | Indicator definitions: IY, CRI, LAS, EE, OR... |
sf technicals [slug] | Technical analysis methodology |
sf opinions [slug] | Published market commentary |
sf blog [slug] | Blog articles + research notes |
sf forum channels | Forum channels + subscription state |
sf forum inbox | Unread messages |
sf forum post <ch> "msg" | Post to a channel |
sf watchlist | Saved markets (--add/--remove) |
sf calendar | Structured event calendar |
sf yield-curve [event] | Implied yield curves |
Intents + Execution:
| Command | What it does |
|---|---|
sf intent buy <ticker> <qty> --price <cents> | Create buy intent with trigger |
sf intent sell <ticker> <qty> --trigger below:40 | Sell intent with price trigger |
sf intent list | Active intents (--all for history) |
sf intent status <id> | Detailed status with fills |
sf intent cancel <id> | Cancel an intent |
sf runtime start [--daemon] [--smart] | Start execution daemon (--smart for LLM intelligence) |
sf runtime stop | Stop daemon |
sf runtime status | Runtime state + active intents |
Portfolio + trading:
| Command | What it does |
|---|---|
sf positions | Kalshi + Polymarket positions with P&L |
sf balance | Account balance |
sf orders | Current resting orders |
sf fills | Recent trade fills |
sf settlements | Settled contracts with P&L |
sf performance | P&L over time with sparklines |
sf buy <ticker> <qty> --price <cents> | Buy contracts (direct, no intent) |
sf sell <ticker> <qty> --price <cents> | Sell contracts (direct, no intent) |
sf cancel [orderId] | Cancel orders (--all for all) |
X / Twitter:
| Command | What it does |
|---|---|
sf x "iran oil" | Search X discussions — posts, sentiment, themes |
sf x-volume "tariffs" | Discussion volume trend with histogram |
sf x-news "tariffs" | X news stories with ticker mentions |
sf x-account @federalreserve | Recent posts from a specific account |
Flags: --json on all commands · --share on scan, query, context, edges, markets, explore
Full reference in the Agent Guide.
Agent Contract {#agent-contract}
The CLI is designed for agent consumption. Behaviors agents can rely on:
| Behavior | Detail |
|---|---|
| Structured errors | When piped (non-TTY), errors emit JSON on stderr: {{"error": "...", "code": "..."}} |
| Exit codes | 0 success, 127 unknown command |
| NO_COLOR | Set NO_COLOR=1 to strip all ANSI escape codes |
| FORCE_COLOR | Set FORCE_COLOR=1 to force ANSI even when piped |
| SF_AUTO_CONFIRM | Set SF_AUTO_CONFIRM=1 to skip interactive confirmations (required for non-TTY order execution) |
| --json | Every command supports --json for structured output |
| LLM fallback | Unrecognized commands get LLM-powered suggestions (e.g., sf thesis list → suggests sf list) |
| --quiet | Suppress non-essential output (progress, banners) |
| sf describe --all --json | Machine-readable catalog of every tool — args, options, auth, side effects |
Agent Harness {#agent-harness}
Tools for testing, backtesting, and constraining agent behavior.
| Command | What it does |
|---|---|
sf agent --record-trace /tmp/trace.ndjson | Record every tool call + LLM message to NDJSON file |
sf agent --replay-trace /tmp/trace.ndjson | Replay: tool calls return recorded output (deterministic) |
sf agent --budget-usd 5 | Hard ceiling on total spend (LLM + side effects) |
sf agent --allow read,query | Whitelist: only these tool categories allowed |
sf agent --deny order,position.write | Blacklist: these tools blocked |
sf agent --headless | Tool-only NDJSON mode: expose 95 tools via stdin/stdout, no LLM. For external LLM integration. |
Event Subscription {#events}
Long-lived structured event streams for reactive agents. Replaces polling.
| Command | What it does |
|---|---|
sf subscribe list | Active subscriptions |
sf subscribe cancel <id> | Cancel a subscription |
Event types: market (price_cross, volume_spike, spread_widen, regime_flip), thesis (confidence_drop, confidence_rise, new_signal), position (drawdown, fill, close), portfolio (drawdown, tick_complete, halt), system (runtime.started, runtime.stopped).
Cloud Runtime {#cloud-runtime}
Run your agent runtime in the cloud. Always-on, no local laptop required. BYOK: your keys, encrypted client-side.
| Command | What it does |
|---|---|
sf setup --cloud | Configure cloud runtime: encrypt + upload your API keys |
sf runtime start --remote | Start your cloud container (Fly.io, ~3s cold start) |
sf runtime stop --remote | Stop cloud container (scale to zero) |
sf --remote agent | Run agent command via cloud runtime |
Key encryption: Your API keys are encrypted client-side (Argon2id key derivation) before upload. SimpleFunctions never sees plaintext credentials.
REST API
No auth needed:
| Endpoint | What it does |
|---|---|
GET /api/agent/world | Real-time world model for agents (~800 tokens markdown). Edges, movers, anchors, divergences. |
GET /api/agent/world/delta?since=1h | Incremental world state update — only what changed (~30-50 tokens). |
GET /api/agent/inspect/:ticker | Complete ticker dossier: price, regime, indicators, suggestion, contagion, 7d trend. |
GET /api/public/query?q=... | LLM-enhanced search (Kalshi + Polymarket + X + traditional) |
GET /api/public/scan?q=... | Cross-venue market search with relevance ranking |
GET /api/public/screen?sort=iy&limit=10 | Indicator screener: filter 50K+ markets by IY, EE, OR, LAS, CRI, RV, VR, IAR, Adj IY, Residual VR, τ |
GET /api/public/ideas | Trade ideas: S&T-style pitches with conviction + catalyst. ?q=topic for on-demand. |
GET /api/public/contagion?window=6h | Cross-market contagion: which connected markets should move but haven't? |
GET /api/public/query-gov?q=... | Legislative intelligence: bills, nominations, members, CRS reports + prediction market cross-reference |
GET /api/public/query-econ?q=... | Official economic data search: FRED-backed time series, latest values, changes, tags. includeMarkets=true adds related prediction markets. |
GET /api/public/legislation | Bills listing with market cross-reference. ?q=, ?hasMarket=true |
GET /api/public/legislation/:billId | Bill detail: status, actions, CRS summary, sponsors + linked markets + state bills |
GET /api/public/congress/members | Current members of Congress. ?state=, ?party=, ?chamber= |
GET /api/public/congress/member/:id | Member detail: bio, sponsored bills, election markets |
GET /api/public/index | SF Prediction Market Index v2: disagreement, geo_risk, breadth, activity |
GET /api/public/index/history?days=7 | Historical index data (1-30 days) |
GET /api/public/newmarkets | Recently listed markets across venues |
GET /api/public/yield-curves | Calendar yield curves — term structure across event families |
GET /api/public/calibration | Brier score calibration metrics across 60K+ resolved markets |
GET /api/public/highlights | Today's market headlines and highlights |
GET /api/public/market/:ticker | Single market detail: price, spread, volume, orderbook (?depth=true) |
GET /api/public/regime/scan | Markets by adverse selection regime (maker/taker/neutral) |
GET /api/public/diff?tickers=X,Y&window=24h | Market derivatives: price/volume/spread/depth deltas + divergence signals |
GET /api/public/briefing?topic=iran | Daily topic briefing: what changed, why it matters, outlook |
GET /api/changes?since=&q=&type= | Server-side market change detection (every 15 min) |
GET /api/tools | Full capability manifest for agent auto-discovery |
GET /api/public/trad-markets | Traditional market snapshot (SPY, VIX, GLD, TLT, USO via Databento) |
GET /api/public/theses | List public theses |
GET /api/public/thesis/:slug | Public thesis detail with causal tree + edges |
GET /api/public/opinions | Opinion articles (/:slug for detail) |
GET /api/public/technicals | Technical analysis (/:slug for detail) |
GET /api/public/glossary | Glossary entries (/:slug for detail) |
GET /api/public/skills | Agent cognitive skills and workflows |
POST /api/monitor-the-situation/enrich | Paste text + topics → prediction market divergence analysis. No auth needed. |
Auth required (Authorization: Bearer sf_live_xxx):
| Endpoint | What it does |
|---|---|
POST /api/monitor-the-situation | Universal web intelligence: scrape any URL (Firecrawl), cross-reference with markets. Requires auth. |
GET /api/edges | Aggregated edges across all theses (auth adds private theses) |
X / Twitter (no auth):
| Endpoint | What it does |
|---|---|
GET /api/x/search?q=... | Search X discussions — posts, sentiment, themes |
GET /api/x/volume?q=... | Discussion volume trend — timeseries, velocity |
GET /api/x/news?q=... | X news stories — headlines, summaries |
GET /api/x/account?username=... | Recent posts from a specific account |
Auth required (Authorization: Bearer sf_live_xxx):
| Endpoint | What it does |
|---|---|
POST /api/thesis/create[?sync=true] | Create thesis (sync waits for formation) |
GET /api/thesis/:id/context | Thesis-specific snapshot |
GET /api/thesis/:id/changes?since=ISO | Lightweight delta check (~50 bytes) |
POST /api/thesis/:id/signal | Inject signal |
POST /api/thesis/:id/evaluate | Force evaluation (up to 2 min) |
POST /api/thesis/:id/augment | Tree augmentation (?dryRun=true to preview) |
POST /api/thesis/:id/strategies | Create trading strategy |
GET /api/thesis/:id/strategies | List strategies |
POST /api/intents | Create execution intent with trigger conditions |
GET /api/intents | List intents (?active=true for active only) |
DELETE /api/intents/:id | Cancel an intent |
GET /api/thesis/:id/evaluations | Daily-aggregated evaluation history (confidence trajectory) |
POST /api/thesis/:id/nodes/update | Direct causal tree node mutation (zero LLM cost) |
GET /api/feed?hours=24 | Evaluation history |
POST /api/skill | Create a custom skill |
GET /api/skill | List user skills + built-in skills |
PUT /api/skill/:id | Update a skill |
DELETE /api/skill/:id | Delete a skill |
POST /api/skill/:id/publish | Publish skill (set slug) |
POST /api/skill/:id/fork | Fork a public skill into your collection |
POST /api/thesis/:id/fork | Fork a public thesis (accepts ID or slug, copies thesis + causal tree) |
Full endpoint reference in the Agent Guide.
Real-Time Data API {#realtime-data-api}
Sub-second WebSocket and REST data feed at data.simplefunctions.dev/v1/ — a separate
surface from the agent / public APIs above. Built for trading agents, dashboards, quants,
and risk engines that need tick-level state across Kalshi and Polymarket.
REST (no auth required at the edge — rate-limited):
| Endpoint | What it does | Cache-Control |
|---|---|---|
GET /v1/markets | All tracked markets with precomputed heat score | public, max-age=3, swr=10 |
GET /v1/markets/featured?n=20 | Top-N by heat — what is moving right now | public, max-age=3, swr=10 |
GET /v1/markets/{ticker} | Single market snapshot with full metadata | public, max-age=2, swr=5 |
GET /v1/orderbook/{ticker} | Live depth — bids, asks, timestamp | public, max-age=1 |
GET /v1/candles/{ticker}?tf=1h&limit=500 | OHLC candles for any timeframe | public, max-age=15 (1d) / 5 (others) |
GET /v1/trades/{ticker}?limit=50 | Recent trade prints, newest first | public, max-age=1 |
GET /v1/heartbeat | System status — markets tracked, ws clients, uptime | public, max-age=10 |
WebSocket (wss://data.simplefunctions.dev/v1/ws, JSON envelopes):
| Topic | Frame shape | Cadence |
|---|---|---|
ticker:{ticker} | {type, ticker, last, bid, ask, volume24h, venue} | On change |
orderbook:{ticker} | {type, ticker, bids, asks, ts} | Throttled 1 Hz |
trade:{ticker} | {type, ticker, price, size, side, ts} | On every print |
candle:{ticker}:{tf} | {type, ticker, timeframe, candle} | On bar update |
featured | {type, markets, generated_at} | 60 s tick + rank-change |
Heat score (0-100 per market): 0.40 × log-vol + 0.35 × spread-tightness + 0.15 × close-to-coin-flip + 0.10 × recent-volatility. Use to filter the long tail — only subscribe to markets above a heat threshold.
curl https://data.simplefunctions.dev/v1/heartbeat
curl https://data.simplefunctions.dev/v1/markets/featured?n=20
const ws = new WebSocket('wss://data.simplefunctions.dev/v1/ws')
ws.addEventListener('open', () => ws.send(JSON.stringify({
action: 'subscribe',
topics: ['featured', 'ticker:KXFEDDECISION-26DEC-CUT100'],
})))
ws.addEventListener('message', e => console.log(JSON.parse(e.data)))
Full marketing + integration page: Real-Time Data API. Agent-specific patterns: Agentic Usage.
Agent Skills
Cognitive guardrails for prediction market agents. Skills are prompts that make agents disciplined.
| Skill | Trigger | What it does |
|---|---|---|
| Discipline | /discipline | Full position review: entry hypothesis, falsification, from-zero test |
| Pre-check | /precheck | Pre-trade adversarial check — argue against the trade first |
| Morning | /morning | Structured daily briefing: kill conditions, positions, action items |
Skills are markdown files. Create your own in ~/.sf/skills/. Browse at /skills.
Agent Runtime
Multi-daemon architecture. Your agent orchestrates background daemons that monitor, reason, and execute autonomously. Smart mode (--smart) adds LLM intelligence: soft condition gating, periodic scans, wake conditions.
sf runtime start --smart --daemon # execution daemon with LLM intelligence
sf telegram --daemon # push notifications + mobile agent
sf agent # interactive agent (reads daemon alerts)
See the Agent Runtime guide for architecture, config, and cost breakdown.
Telegram Bot
sf telegram --token YOUR_BOTFATHER_TOKEN --daemon
Runs locally. Slash commands + natural language. Auto-pushes confidence alerts.
Webhook
Add webhookUrl when creating a thesis. The engine POSTs on confidence changes >= 5%.
Authentication
Get an API key from the Dashboard.
curl -H "Authorization: Bearer sf_live_xxx" https://simplefunctions.dev/api/thesis
For CLI: sf setup stores the key in ~/.sf/config.json. Config priority: env vars > config file > defaults.
Key Concepts
Signals
Events that feed into evaluations. Five types:
| Type | Source | Description |
|---|---|---|
news | Heartbeat or manual | News articles, data releases |
price_move | Heartbeat | Market price change >= 3 cents |
user_note | Manual | Your analysis or observations |
external | Manual | Signals from other systems |
upcoming_event | Heartbeat | Kalshi milestone matching edges |
Edge Types
The system classifies each edge by WHY the mispricing exists:
- consensus_gap — market and thesis disagree on fundamental probability
- attention_gap — market hasn't reacted to recent information yet
- timing_gap — market prices short-term risk, thesis prices long-term outcome
- risk_premium — market embeds fear/greed premium that thesis doesn't
Track Record
Feedback loop that computes how well past edges predicted market movement:
- Hit rate: % of edges where market moved toward the thesis-implied price
- Average movement: mean price change in cents since edge detection
- Track record is injected into evaluation prompts so the system learns from its accuracy
Tree Augmentation
The causal tree evolves over time:
- Each evaluation can suggest new causal factors (
suggestedNodes) - Weekly (Monday 6 UTC), the augment agent reviews suggestions
- LLM decides which to accept (must be genuinely new, not duplicates)
- Accepted nodes are appended (never removed — append-only tree)
- Importance weights are rebalanced among siblings
Kill Conditions
Before every evaluation, the system asks: "Does any event fundamentally break a core assumption of this thesis?" If yes, it flags the threat prominently before any other analysis.
Pricing
Free during beta. Pay by token after 15M tokens consumed.
Full Reference
See the Agent Guide for the complete machine-readable reference — all 54 MCP tools, CLI commands, REST endpoints, context response shape, and integration rules. The guide page has a "Copy everything" button for pasting into agent prompts.