SimpleFunctions

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

Integration

Deep dives


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:

  1. Scans news (3 queries including one adversarial — never filters out contradictory evidence)
  2. Refreshes prices from Kalshi API + Polymarket CLOB
  3. Enriches orderbooks (bid/ask depth for edges > 5 cents)
  4. Evaluates signals against causal tree (checks kill conditions first)
  5. Computes track record (hit rate: % of edges that moved toward thesis)
  6. 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):

CommandWhat it does
sf scan "gold"Search Kalshi + Polymarket
sf scan "btc" --expires-before 24h --price-min 3 --price-max 9Scan with server-side filters (expiry / price / volume)
sf overround "senate majority leader"Sum YES asks across multi-leg event; flag arb
sf newmarkets --hours 24Newly 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" orderbookLive bid/ask/spread/depth tracking
sf watch "gold" flowMomentum detection, volume spikes
sf watch "gold" cross-venueKalshi vs Polymarket spread tracking
sf agentInteractive agent (all tools + skills, explorer mode)
sf contextGlobal market snapshot
sf marketsTraditional markets (SPY, VIX, GLD, TLT, USO)
sf exploreBrowse public theses
sf statusHealth check: API, auth, Kalshi, Polymarket, theses
sf dashboardInteractive Bloomberg-style terminal

Thesis + analysis:

CommandWhat it does
sf thesis create "thesis"Create thesis with causal tree + edges
sf thesis context <id>Thesis-specific snapshot
sf edgesTop 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 feedEvaluation history
sf contagionMarkets that should have moved but didn't
sf cross-venueKalshi vs Polymarket price comparison
sf calibrationBrier scores + calibration metrics
sf regime [ticker]Market regime analysis (--history)

Knowledge + community:

CommandWhat 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 channelsForum channels + subscription state
sf forum inboxUnread messages
sf forum post <ch> "msg"Post to a channel
sf watchlistSaved markets (--add/--remove)
sf calendarStructured event calendar
sf yield-curve [event]Implied yield curves

Intents + Execution:

CommandWhat it does
sf intent buy <ticker> <qty> --price <cents>Create buy intent with trigger
sf intent sell <ticker> <qty> --trigger below:40Sell intent with price trigger
sf intent listActive 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 stopStop daemon
sf runtime statusRuntime state + active intents

Portfolio + trading:

CommandWhat it does
sf positionsKalshi + Polymarket positions with P&L
sf balanceAccount balance
sf ordersCurrent resting orders
sf fillsRecent trade fills
sf settlementsSettled contracts with P&L
sf performanceP&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:

CommandWhat 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 @federalreserveRecent 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:

BehaviorDetail
Structured errorsWhen piped (non-TTY), errors emit JSON on stderr: {{"error": "...", "code": "..."}}
Exit codes0 success, 127 unknown command
NO_COLORSet NO_COLOR=1 to strip all ANSI escape codes
FORCE_COLORSet FORCE_COLOR=1 to force ANSI even when piped
SF_AUTO_CONFIRMSet SF_AUTO_CONFIRM=1 to skip interactive confirmations (required for non-TTY order execution)
--jsonEvery command supports --json for structured output
LLM fallbackUnrecognized commands get LLM-powered suggestions (e.g., sf thesis list → suggests sf list)
--quietSuppress non-essential output (progress, banners)
sf describe --all --jsonMachine-readable catalog of every tool — args, options, auth, side effects

Agent Harness {#agent-harness}

Tools for testing, backtesting, and constraining agent behavior.

CommandWhat it does
sf agent --record-trace /tmp/trace.ndjsonRecord every tool call + LLM message to NDJSON file
sf agent --replay-trace /tmp/trace.ndjsonReplay: tool calls return recorded output (deterministic)
sf agent --budget-usd 5Hard ceiling on total spend (LLM + side effects)
sf agent --allow read,queryWhitelist: only these tool categories allowed
sf agent --deny order,position.writeBlacklist: these tools blocked
sf agent --headlessTool-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.

CommandWhat it does
sf subscribe listActive 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.

CommandWhat it does
sf setup --cloudConfigure cloud runtime: encrypt + upload your API keys
sf runtime start --remoteStart your cloud container (Fly.io, ~3s cold start)
sf runtime stop --remoteStop cloud container (scale to zero)
sf --remote agentRun 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:

EndpointWhat it does
GET /api/agent/worldReal-time world model for agents (~800 tokens markdown). Edges, movers, anchors, divergences.
GET /api/agent/world/delta?since=1hIncremental world state update — only what changed (~30-50 tokens).
GET /api/agent/inspect/:tickerComplete 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=10Indicator screener: filter 50K+ markets by IY, EE, OR, LAS, CRI, RV, VR, IAR, Adj IY, Residual VR, τ
GET /api/public/ideasTrade ideas: S&T-style pitches with conviction + catalyst. ?q=topic for on-demand.
GET /api/public/contagion?window=6hCross-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/legislationBills listing with market cross-reference. ?q=, ?hasMarket=true
GET /api/public/legislation/:billIdBill detail: status, actions, CRS summary, sponsors + linked markets + state bills
GET /api/public/congress/membersCurrent members of Congress. ?state=, ?party=, ?chamber=
GET /api/public/congress/member/:idMember detail: bio, sponsored bills, election markets
GET /api/public/indexSF Prediction Market Index v2: disagreement, geo_risk, breadth, activity
GET /api/public/index/history?days=7Historical index data (1-30 days)
GET /api/public/newmarketsRecently listed markets across venues
GET /api/public/yield-curvesCalendar yield curves — term structure across event families
GET /api/public/calibrationBrier score calibration metrics across 60K+ resolved markets
GET /api/public/highlightsToday's market headlines and highlights
GET /api/public/market/:tickerSingle market detail: price, spread, volume, orderbook (?depth=true)
GET /api/public/regime/scanMarkets by adverse selection regime (maker/taker/neutral)
GET /api/public/diff?tickers=X,Y&window=24hMarket derivatives: price/volume/spread/depth deltas + divergence signals
GET /api/public/briefing?topic=iranDaily topic briefing: what changed, why it matters, outlook
GET /api/changes?since=&q=&type=Server-side market change detection (every 15 min)
GET /api/toolsFull capability manifest for agent auto-discovery
GET /api/public/trad-marketsTraditional market snapshot (SPY, VIX, GLD, TLT, USO via Databento)
GET /api/public/thesesList public theses
GET /api/public/thesis/:slugPublic thesis detail with causal tree + edges
GET /api/public/opinionsOpinion articles (/:slug for detail)
GET /api/public/technicalsTechnical analysis (/:slug for detail)
GET /api/public/glossaryGlossary entries (/:slug for detail)
GET /api/public/skillsAgent cognitive skills and workflows
POST /api/monitor-the-situation/enrichPaste text + topics → prediction market divergence analysis. No auth needed.

Auth required (Authorization: Bearer sf_live_xxx):

EndpointWhat it does
POST /api/monitor-the-situationUniversal web intelligence: scrape any URL (Firecrawl), cross-reference with markets. Requires auth.
GET /api/edgesAggregated edges across all theses (auth adds private theses)

X / Twitter (no auth):

EndpointWhat 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):

EndpointWhat it does
POST /api/thesis/create[?sync=true]Create thesis (sync waits for formation)
GET /api/thesis/:id/contextThesis-specific snapshot
GET /api/thesis/:id/changes?since=ISOLightweight delta check (~50 bytes)
POST /api/thesis/:id/signalInject signal
POST /api/thesis/:id/evaluateForce evaluation (up to 2 min)
POST /api/thesis/:id/augmentTree augmentation (?dryRun=true to preview)
POST /api/thesis/:id/strategiesCreate trading strategy
GET /api/thesis/:id/strategiesList strategies
POST /api/intentsCreate execution intent with trigger conditions
GET /api/intentsList intents (?active=true for active only)
DELETE /api/intents/:idCancel an intent
GET /api/thesis/:id/evaluationsDaily-aggregated evaluation history (confidence trajectory)
POST /api/thesis/:id/nodes/updateDirect causal tree node mutation (zero LLM cost)
GET /api/feed?hours=24Evaluation history
POST /api/skillCreate a custom skill
GET /api/skillList user skills + built-in skills
PUT /api/skill/:idUpdate a skill
DELETE /api/skill/:idDelete a skill
POST /api/skill/:id/publishPublish skill (set slug)
POST /api/skill/:id/forkFork a public skill into your collection
POST /api/thesis/:id/forkFork 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):

EndpointWhat it doesCache-Control
GET /v1/marketsAll tracked markets with precomputed heat scorepublic, max-age=3, swr=10
GET /v1/markets/featured?n=20Top-N by heat — what is moving right nowpublic, max-age=3, swr=10
GET /v1/markets/{ticker}Single market snapshot with full metadatapublic, max-age=2, swr=5
GET /v1/orderbook/{ticker}Live depth — bids, asks, timestamppublic, max-age=1
GET /v1/candles/{ticker}?tf=1h&limit=500OHLC candles for any timeframepublic, max-age=15 (1d) / 5 (others)
GET /v1/trades/{ticker}?limit=50Recent trade prints, newest firstpublic, max-age=1
GET /v1/heartbeatSystem status — markets tracked, ws clients, uptimepublic, max-age=10

WebSocket (wss://data.simplefunctions.dev/v1/ws, JSON envelopes):

TopicFrame shapeCadence
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.

SkillTriggerWhat it does
Discipline/disciplineFull position review: entry hypothesis, falsification, from-zero test
Pre-check/precheckPre-trade adversarial check — argue against the trade first
Morning/morningStructured 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:

TypeSourceDescription
newsHeartbeat or manualNews articles, data releases
price_moveHeartbeatMarket price change >= 3 cents
user_noteManualYour analysis or observations
externalManualSignals from other systems
upcoming_eventHeartbeatKalshi 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:

  1. Each evaluation can suggest new causal factors (suggestedNodes)
  2. Weekly (Monday 6 UTC), the augment agent reviews suggestions
  3. LLM decides which to accept (must be genuinely new, not duplicates)
  4. Accepted nodes are appended (never removed — append-only tree)
  5. 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.