SimpleFunctions Agent Reference
Prediction market intelligence engine. Your agent reads thesis state, injects observations, and reacts to edge changes. The backend handles news scanning, price monitoring, and evaluation continuously.
Venues: Kalshi + Polymarket. All prices in cents (0-100).
Connect
MCP (recommended for Claude Code, Cursor, Cline)
claude mcp add simplefunctions --url https://simplefunctions.dev/api/mcp/mcp
For Cursor/Cline, add to MCP config:
{"mcpServers": {"simplefunctions": {"url": "https://simplefunctions.dev/api/mcp/mcp"}}}
CLI
npm install -g @spfunctions/cli
sf setup # interactive wizard, 2 min
Every command supports --json for machine-readable output.
REST API
Base URL: https://simplefunctions.dev. Auth: Authorization: Bearer sf_live_xxx.
Core Workflow
No thesis needed — start here
# Global market snapshot — movers, expiring, milestones, liquidity
sf context --json
# LLM-enhanced knowledge search — markets + content + synthesized answer
sf query "iran oil" --json
With a thesis — richer context
# 1. READ — thesis state (causal tree, edges, orderbook, evaluation)
sf context <id> --json
# 2. WRITE — inject your observations
sf signal <id> "Iran deploys coastal missiles near Hormuz" --type news
# 3. REACT — force deep analysis when something big happens
sf evaluate <id>
For efficient polling, use the delta endpoint instead of full context:
GET /api/thesis/:id/changes?since=2026-03-23T00:00:00Z
# Nothing changed: {"changed": false} — 50 bytes
# Changed: {"changed": true, "confidence": 0.89, "confidenceDelta": 0.02, ...}
MCP Tools (44)
| Tool | What it does | Auth |
|---|---|---|
get_world_state | Real-time world model (~800 tokens): prediction index, traditional markets, topic summaries, divergences. ?focus=energy,geo for deeper coverage | No |
get_world_delta | Incremental world state update — only what changed since timestamp (~30-50 tokens) | No |
monitor_the_situation | Universal web intelligence: scrape any URL (Firecrawl), analyze with any LLM, cross-reference with thousands of markets, push to webhook | Yes |
enrich_content | Paste text + topics → prediction market divergence analysis. No Firecrawl needed. Free (rate limited), or pass API key for no limit. | No |
get_trade_ideas | S&T-style trade pitches: conviction, catalyst, direction, risk | No |
get_context | Without thesisId: global market snapshot. With thesisId: thesis-specific context | Optional |
query | LLM-enhanced prediction market knowledge search (Kalshi + Polymarket + X + traditional + content) | No |
list_theses | All theses with status, confidence, position count | Yes |
create_thesis | Create thesis, run formation (causal tree + market scan + edges) | Yes |
inject_signal | Feed an observation into the thesis signal queue | Yes |
trigger_evaluation | Force immediate evaluation with heavy model | Yes |
augment_tree | Review suggested nodes from evaluations, merge into causal tree | Yes |
update_nodes | Directly set causal tree node probabilities (zero LLM). The lock field is advisory — pins a node as stable but evidence can still revise it. | Yes |
fork_thesis | Clone a public thesis OR evolve your own into a new frame (pass newRawThesis). Evolve-mode parks the parent in dormant mode and re-runs formation on the child. | Yes |
what_if | Override node probabilities, see edge impact (zero LLM cost) | Yes |
update_thesis | Update title, status (active/paused/archived), webhookUrl | Yes |
configure_heartbeat | Adjust heartbeat: news interval, model tier, budget, pause/resume | Yes |
get_heartbeat_status | Heartbeat config + monthly cost summary | Yes |
get_evaluation_history | Confidence trajectory over time (daily aggregated) | Yes |
add_position | Record a new position for tracking | Yes |
update_position | Update position: price, edge, status (open→closed) | Yes |
close_position | Remove a position record | Yes |
scan_markets | Search Kalshi + Polymarket by keyword | No |
explore_public | Browse published theses | No |
create_strategy | Define trading strategy with entry/exit/sizing rules | Yes |
list_strategies | List strategies for a thesis | Yes |
update_strategy | Update strategy parameters or status | Yes |
create_intent | Declare execution intent with trigger conditions | Yes |
list_intents | List intents: pending, armed, triggered, filled | Yes |
cancel_intent | Cancel an active intent | Yes |
get_edges | Aggregated edges sorted by | executableEdge |
get_milestones | Upcoming Kalshi calendar events | No |
get_forecast | P50/P75/P90 market distribution | Yes |
get_settlements | Settled contracts with realized P&L | Yes |
get_balance | Account balance | Yes |
get_orders | Current resting orders | Yes |
get_fills | Recent trade executions | Yes |
get_markets | Traditional market prices (SPY, VIX, Treasury, Gold, Oil via Databento) | No |
get_schedule | Exchange trading hours and status | No |
search_x | Search X discussions — posts, sentiment, volume, news | No |
x_volume | Discussion volume trend — timeseries, velocity, peak detection | No |
x_news | X news stories — headlines, summaries, ticker mentions | No |
x_account | Recent posts from a specific X account | No |
browse_public_skills | Browse community skills: filter by category, search, sort by popular/new | No |
create_skill | Create a custom agent skill (reusable prompt triggered via slash command) | Yes |
list_skills | List built-in + user-created skills | Yes |
run_skill | Get skill by ID to retrieve prompt and metadata for execution | Yes |
publish_skill | Publish a skill for community browsing and forking | Yes |
fork_skill | Fork a public skill into your collection | Yes |
fork_thesis | Fork a public thesis: copies thesis + causal tree, run formation for fresh edges | Yes |
daemon_command | Send command to running daemon (runtime, telegram): pause, resume, scan_now | Yes |
set_wake_condition | Set alert condition: price threshold, time, or natural language (LLM-evaluated) | Yes |
check_daemon_alerts | Read alerts and observations from running daemons | Yes |
Tools marked "No" work without an API key. get_context works both ways.
CLI Commands (43)
Thesis
| Command | Description |
|---|---|
sf thesis list [--json] | List all theses |
sf thesis get <id> [--json] | Full thesis details |
sf thesis context <id> [--json] | Thesis snapshot — primary read endpoint for agents |
sf thesis create "thesis text" [--async] | Create new thesis (sync waits for formation) |
sf thesis signal <id> "content" [--type news] | Inject signal (types: news, user_note, external, price_move, upcoming_event) |
sf thesis evaluate <id> | Trigger deep evaluation (heavy model) |
sf thesis augment <id> [--dry-run] | Review + merge suggested causal tree nodes |
sf prompt [id] | Get dynamic system prompt with live thesis state |
sf thesis publish <id> --slug <slug> | Publish thesis publicly |
sf thesis unpublish <id> | Remove from public |
Markets
| Command | Description |
|---|---|
sf scan "keywords" | Search Kalshi + Polymarket (no auth needed) |
sf scan --series TICKER | Browse series events + prices |
sf scan --market TICKER | Single market detail |
sf scan "btc" --expires-before 24h --price-min 3 --price-max 9 --vol24h-min 100 | Server-side filters: expiry window, price range, volume floor |
sf scan "governor" --include-subcent | Surface markets trading below 1¢ (priceMillicents) |
sf book <ticker> [ticker2...] | Orderbook depth, spread, liquidity (accepts kalshi:/poly: prefix or bare ticker) |
sf book --poly "oil price" | Search + show Polymarket orderbooks |
sf overround <event> | Sum YES asks across multi-leg event; flag arb when total ≠ 100¢ |
sf newmarkets [--hours 24] [--venue polymarket] [--min-liquidity 1000] | Newly listed markets in last N hours |
sf screen [--iy-min 200] [--tau-max 7] [--without-thesis] | Indicator screener: filter universe by IY, EE, OR, LAS, CRI, RV, VR, IAR, Adj IY, Residual VR, τ — the math labels behind every strategy |
sf screen --or-min 0.05 | Find events whose YES legs sum to ≥ 105% — book-maker margin or live arb |
sf screen --without-thesis --venue polymarket | Unloved Polymarket markets — strategy 2/3 long-tail entry |
sf edges [--json] | Top edges across all theses |
sf whatif <id> --set "n1=0.1" | What-if scenario (zero LLM cost) |
sf liquidity [topic] | Orderbook scanner across 18 topics |
sf explore [slug] | Browse public theses (no auth) |
sf forecast <eventTicker> | P50/P75/P90 market distribution |
sf milestones | Upcoming Kalshi calendar events |
sf install-completion | Install zsh tab completion (one-shot) |
Analysis
| Command | Description |
|---|---|
sf contagion [--window 6h] | Markets that should have moved but didn't (contagion gaps) |
sf cross-venue [--preset arb] | Kalshi vs Polymarket price comparison |
sf yield-curve [event] | Implied yield curve for multi-outcome events |
sf calibration | Brier scores + calibration metrics on settled markets |
sf regime [ticker] [--history] | Market regime analysis |
sf calendar | Structured event calendar |
Knowledge
| Command | Description |
|---|---|
sf concepts [slug] | Prediction market concepts + indicator definitions |
sf technicals [slug] | Technical analysis methodology |
sf opinions [slug] | Published market commentary |
sf blog [slug] | Blog articles + research notes |
Forum + Tracking
| Command | Description |
|---|---|
sf forum channels | List channels + subscription state |
sf forum inbox | Unread messages across subscriptions |
sf forum post <channel> "message" | Post to a channel |
sf forum join <channel> | Subscribe to a channel |
sf watchlist [--add/--remove <ticker>] | Manage saved markets |
sf discuss <topic> | Public market discussion |
Portfolio
| Command | Description |
|---|---|
sf positions | Kalshi + Polymarket positions with thesis edge overlay |
sf balance | Account balance |
sf orders | Resting orders |
sf fills | Recent trade fills |
sf settlements | Settled contracts with P&L |
sf performance | P&L over time with sparklines |
sf status | Health check: API, auth, Kalshi, Polymarket, theses, trading |
sf dashboard | Interactive Bloomberg-style TUI (j/k navigate, Enter detail, l liquidity, w what-if) |
sf feed [--hours 24] | Evaluation history stream |
Intents + Execution
| Command | Description |
|---|---|
sf intent buy <ticker> <qty> --price <cents> | Create buy intent |
sf intent sell <ticker> <qty> --trigger below:40 | Sell intent with price trigger |
sf intent list [--all] | 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 enables LLM intelligence) |
sf runtime stop | Stop daemon |
sf runtime status | Runtime state + active intents |
Watch (smart monitoring)
| Command | Description |
|---|---|
sf watch "query" [mode] | Modes: (default), orderbook, flow, cross-venue, all |
sf watch "fed" orderbook | Live bid/ask/spread/depth tracking (30s poll) |
sf watch "fed" flow | Momentum detection, volume spikes, reversals |
sf watch "fed" cross-venue | Kalshi vs Polymarket spread tracking |
sf watch "fed" all | All modes combined |
Agent Runtime (smart daemons)
The agent runtime is a multi-daemon architecture. Your main agent (sf agent) orchestrates background daemons that monitor, reason, and execute autonomously.
Architecture:
- Main agent (
sf agent) — interactive TUI, sets wake conditions, reads daemon alerts - Runtime daemon (
sf runtime start --smart --daemon) — evaluates intent triggers, LLM-gates soft conditions, periodic smart scans - Telegram daemon (
sf telegram --daemon) — push notifications, agent bridge for mobile - Watch daemon (
sf watch) — market monitoring across modes
Smart mode (--smart) adds an LLM intelligence layer to daemons:
- Soft conditions: Intents can have natural language conditions (e.g. "only if oil above $95"). When a hard trigger fires, the runtime asks a cheap LLM whether the soft condition is met before executing.
- Periodic scan: Every ~5 minutes, the runtime summarizes all active intents + market state and sends observations to the agent via the message bus.
- Wake conditions: The agent can set rules for when to be alerted — price thresholds, time triggers, or natural language conditions evaluated by LLM.
Communication: File-based message bus for IPC. Daemons write observations; the agent reads them. The agent writes commands; daemons read them. Agent presence detected via heartbeat file.
Config (~/.sf/config.json):
{
"smartDaemons": true,
"smartModel": "your-preferred-model",
"smartScanInterval": 10,
"smartBudgetUsd": "your_budget"
}
| Agent Tool | Description |
|---|---|
daemon_command | Send command to daemon: pause, resume, scan_now |
set_wake_condition | Price, time, or LLM-evaluated alert condition |
check_daemon_alerts | Read daemon observations and alerts |
Trading (requires sf setup --enable-trading)
| Command | Description |
|---|---|
sf buy <ticker> <qty> --price <cents> | Buy contracts directly (3s countdown) |
sf sell <ticker> <qty> --price <cents> | Sell contracts directly |
sf cancel [orderId] | Cancel order(s) |
sf rfq <ticker> <qty> | Request for quote (large orders) |
Query & X
| Command | Description |
|---|---|
sf query "gold price" | LLM-enhanced knowledge search — Kalshi + Polymarket + X + traditional + content |
sf query "fed rate" --json | JSON output for agents |
sf x "oil" | Search X discussions — posts, sentiment, themes |
sf x-volume "oil" | Discussion volume trend with histogram |
sf x-news "oil" | X news stories with ticker mentions |
sf x-account @zerohedge | Recent posts from a specific account |
Other
| Command | Description |
|---|---|
sf setup | Interactive config wizard |
sf agent [id] | Interactive agent (natural language + 95 tools) |
sf agent --headless | Tool-only mode: NDJSON stdin/stdout protocol, no LLM. External LLM integration. |
sf agent --record-trace /tmp/t.ndjson | Record all tool calls + LLM messages to NDJSON |
sf agent --replay-trace /tmp/t.ndjson | Replay recorded tool outputs (deterministic backtest) |
sf agent --budget-usd 5 --deny order | Constrained agent: spending ceiling + permission capsule |
sf describe [tool] --json | Machine-readable tool schema. --all for full 95-tool catalog. |
sf subscribe list | Active event subscriptions |
sf --remote <cmd> | Route any command through cloud runtime (Fly.io) |
sf setup --cloud | Encrypt + upload exchange keys for cloud runtime (BYOK) |
sf telegram | Telegram bot for monitoring |
sf schedule | Exchange status |
sf announcements | Exchange announcements |
sf history <ticker> | Historical market data |
Global Flags
| Flag | Description |
|---|---|
--json | JSON output (prefix or suffix: sf --json world or sf world --json) |
--quiet | Suppress progress output (banners, spinners) |
--remote | Route command through cloud runtime |
REST API Endpoints
All require Authorization: Bearer sf_live_xxx unless noted.
Thesis
| Method | Endpoint | Description |
|---|---|---|
POST | /api/thesis/create[?sync=true] | Create thesis. Sync waits up to 5 min. |
GET | /api/thesis/:id/context | Thesis snapshot (primary read endpoint) |
GET | /api/thesis/:id/changes?since=ISO | Lightweight delta check (~50 bytes if no change) |
POST | /api/thesis/:id/signal | Inject signal. Body: {"type":"news","content":"...","source":"agent"} |
POST | /api/thesis/:id/evaluate | Force evaluation (heavy model, up to 2 min) |
POST | /api/thesis/:id/augment[?dryRun=true] | Review + merge suggested tree nodes |
POST | /api/thesis/:id/nodes/update | Direct node mutation (zero LLM cost). lock is advisory (pin, not freeze). Body: {"updates":[{"nodeId":"n3","probability":0.99}],"lock":["n3"]} |
POST | /api/thesis/:id/fork | Clone (empty body) or Evolve ({newRawThesis, newTitle?, reason?, inheritEdgeMarketIds?}). Evolve parks parent in dormant; child re-runs formation. |
GET | /api/thesis/:id/evaluations[?limit=200] | Daily-aggregated evaluation history. Each row carries optional evolutionType (stable, refinement, fork, large_move) for gitMode theses. |
GET | /api/thesis/:id/prompt[?sections=thesis,edges&maxLength=3000] | Dynamic system prompt |
GET | /api/thesis | List all theses |
PATCH | /api/thesis/:id | Update status, webhookUrl, metadata |
DELETE | /api/thesis/:id | Delete thesis |
Feed & Prompt
| Method | Endpoint | Description |
|---|---|---|
GET | /api/feed?hours=24&limit=200 | Evaluation history stream |
GET | /api/prompt[?maxLength=4000] | Combined prompt for all active theses |
Intents & Execution
| Method | Endpoint | Description |
|---|---|---|
POST | /api/intents | Create execution intent with trigger conditions |
GET | /api/intents[?active=true&status=&venue=] | List intents |
GET | /api/intents/:id | Intent detail with fills |
DELETE | /api/intents/:id | Cancel an intent |
Public (no auth)
| Method | Endpoint | Description |
|---|---|---|
GET | /api/agent/world | Real-time world model (~800 tokens). Anchor contracts always present. ?focus=energy,geo for deeper topic coverage. |
GET | /api/agent/world/delta?since=1h | Incremental update (~30-50 tokens). Only what changed since timestamp. |
GET | /api/public/theses | List published theses |
GET | /api/public/thesis/:slug | Full public thesis data |
GET | /api/public/ideas | Trade ideas: S&T-style pitches (12h cache) |
GET | /api/public/ideas/:id | Single idea with live market data |
GET | /api/public/trad-markets | Traditional market prices (SPY, VIX, GLD, TLT, USO) |
GET | /api/public/scan?q=...[&venue=&limit=] | Cross-venue market search with relevance ranking |
GET | /api/public/market/:ticker[?depth=true] | Single market profile: price, spread, volume, orderbook, thesis edges |
GET | /api/public/index[?history=true] | SF Index v2: disagreement (0-100), geo_risk (0-100, signed basket), breadth (-1..+1), activity (0-100 percentile) |
GET | /api/public/contagion[?topic=iran&window=6h] | Cross-market contagion: movers + lagging connected markets + gap size |
GET | /api/public/diff?tickers=X,Y&window=24h | Market derivatives: price/volume/spread/depth deltas over time window |
GET | /api/public/briefing?topic=iran[&window=24h] | Daily topic briefing with LLM synthesis (10 topics available) |
GET | /api/edges | Aggregated edges across all theses (public subset without auth) |
Context Response Shape
GET /api/thesis/:id/context returns:
{
"thesisId": "f582bf76-...",
"thesis": "Trump cannot exit the Iran war gracefully...",
"status": "active",
"confidence": 0.82,
"causalTree": {
"rootClaim": "...",
"nodes": [
{"id": "n1", "label": "...", "probability": 0.85, "importance": 0.3, "depth": 0, "childCount": 3}
]
},
"edges": [
{
"marketId": "KXRECSSNBER-26",
"market": "Will there be a recession in 2026?",
"venue": "kalshi",
"direction": "yes",
"marketPrice": 34,
"thesisPrice": 55,
"edge": 21,
"executableEdge": 20,
"orderbook": {"bidPrice": 33, "askPrice": 35, "spread": 2, "bidDepth": 814, "askDepth": 500, "liquidityScore": "high"}
}
],
"lastEvaluation": {
"summary": "...",
"confidenceDelta": 0.10,
"updatedNodes": [{"nodeId": "n3", "previousProbability": 0.6, "newProbability": 0.75, "reason": "..."}]
},
"suggestedTreeExtensions": [
{"label": "...", "description": "...", "parentNodeId": "n2", "estimatedProbability": 0.7}
],
"trackRecord": {
"hitRate": 67,
"edgesTracked": 49,
"movedToward": 33,
"movedAway": 16,
"avgMovement": 3,
"bestEdge": {"market": "...", "delta": 21},
"worstEdge": {"market": "...", "delta": -12}
}
}
What The Backend Does Automatically
The heartbeat engine runs every 15 minutes for each active thesis. Your agent does NOT need to do any of this:
- News scan — 3 targeted queries (including one adversarial/contrarian). Filters with cheap LLM. Never excludes contradictory news.
- Price rescan — Live prices from Kalshi API + Polymarket CLOB. Injects changes >= 3 cents.
- Orderbook enrichment — Bid/ask/depth for edges with |edge| > 5 cents.
- Evaluation — LLM evaluates signals against causal tree. Checks kill conditions first. Updates node probabilities and confidence.
- Track record — Computes batting average (edges that moved toward the thesis) and injects into next evaluation as feedback loop.
5b. Evolution classification (gitMode) — The LLM classifies each cycle as
stable,refinement, ordiscontinuous. Discontinuous cycles auto-fork into a new child thesis with the same market coverage; parent enters dormant. - Edge discovery — Daily (6 UTC): scans for new markets matching thesis.
- Tree augmentation — Weekly (Monday 6 UTC): reviews suggested nodes, merges accepted ones (append-only).
- Settlement sync — Checks settled contracts, records realized returns.
- Strategy review — Reviews strategies against updated edges.
Edge diagnosis types
Each edge is classified as: consensus_gap (market/thesis disagree), attention_gap (market hasn't reacted), timing_gap (short vs long term), or risk_premium (fear/greed premium).
Kill conditions
Before every evaluation: "Does any event fundamentally break a core assumption?" If yes, flags prominently.
Rules for Agents
- Don't poll prices — the heartbeat does it every 15 min
- Don't search news — the heartbeat does it with adversarial queries
- Do inject observations immediately —
inject_signalwith typeuser_noteornews - Only call
evaluatefor breaking events — routine evaluation is automatic - Use
what_ifbefore trades — zero LLM cost scenario analysis - Call
get_positionsbefore discussing trades — positions are local (Kalshi private key), backend can't see them - Use
/changesfor polling — 100x smaller than full context - Use short thesis IDs — first 8 chars work everywhere (e.g.
f582bf76)
Writing good theses
- Be specific and directional: "Oil stays above $100 for 6 months" not "Oil prices"
- Include timeframe: helps match contracts
- One thesis = one view: don't mix unrelated predictions
Signal types
| Type | When to use |
|---|---|
news | External events, articles, data releases |
user_note | Your agent's own analysis or observations |
external | Signals from other systems |
price_move | Auto-injected by heartbeat (>= 3 cent change) |
upcoming_event | Auto-injected by heartbeat (Kalshi milestone matching edges) |
Interactive Agent
sf agent [id] launches a natural language session with 40+ tools. Supports TUI mode (default) and plain mode (--plain for pipes).
Slash commands: /tree, /edges, /pos, /eval, /buy TICKER QTY PRICE, /sell, /cancel, /switch <id>, /compact, /model <name>, /exit.
Sessions persist at ~/.sf/sessions/. Use --new for fresh session.
Telegram Bot
sf telegram --token TOKEN — runs locally, credentials stay on your machine.
Commands: /context, /positions, /edges, /balance, /orders, /eval, /list, /switch.
Natural language works too — same tools as sf agent. Auto-pushes confidence alerts every 60s.
Webhook
Configure when creating thesis: {"rawThesis": "...", "webhookUrl": "https://..."}
POSTs on confidence changes >= 5% and non-hold position recommendations.