SimpleFunctions

Agentic Usage.

AI agents on real-time prediction market data — Claude Code, tool-use, custom WebSocket bots.

Subscribe once, react to ticks, act through your venue. Agentic usage of the SimpleFunctions data API replaces poll-and-pray with a sub-second WebSocket the agent observes the same way the venue does. Patterns, code samples, and the operational primitives below.

Vertical-split image — top half realist oil painting of a 1940s Roosevelt-era US Congress chamber, bottom half a Claude Code terminal user interface — deliberation by humans contrasted with deliberation by agents

Deliberation by humans, then deliberation by agents — same loop, faster.

Common agent patterns

Six concrete shapes for agentic usage. Every one collapses to the same primitive — subscribe, react, act — but the policy in the middle differs.

Tick-driven trading agent

Subscribe to ticker + orderbook for active positions. On every frame, evaluate signal logic, place or amend at the venue.

WS subscribe ticker:* + orderbook:* → agent loop → venue order

Heat-driven research agent

LLM polls featured every 60 s, summarizes the top-N rank changes for a human analyst or upstream pipeline.

GET /v1/markets/featured → LLM summarize → notify

Autonomous risk gate

Heartbeat + featured watcher. Compare current heat distribution vs baseline; alert and pause sibling agents on regime shift.

GET /v1/heartbeat + GET /v1/markets/featured → policy → halt

Hedge-construction agent

Given an exposure description, query candidate markets, inspect depth, surface the top 3 hedge candidates with sized recommendations.

GET /v1/markets + GET /v1/orderbook/{ticker} → LLM rank → output

Backtest agent

Pull historical candles per timeframe; reconstruct tick replay from trade prints; run a strategy evaluator without touching production.

GET /v1/candles + GET /v1/trades → simulate

World-model context loader

Inject the featured stream as compact context for an upstream LLM agent — what is hot right now, in one frame per minute.

WS subscribe featured → LLM context window

The agent loop — subscribe, react, act

Three primitives. Every agentic usage of the SimpleFunctions data API collapses to this shape. Policy and venue routing differ; the loop is constant.

01

Subscribe

Open one WebSocket. Send a topics array — featured, ticker:*, orderbook:*, trade:*, candle:*. The server fans out frames from the underlying Kalshi + Polymarket ingest.

wss://data.simplefunctions.dev/v1/ws

02

React

On each frame, your agent evaluates: a price moved? a heat ranking changed? a signal threshold crossed? Reactive logic runs on push, not on poll.

frame.type === "ticker" → policy(frame)

03

Act

Take action through your venue connection (Kalshi, Polymarket) or upstream system. SimpleFunctions does not broker — execution stays at the venue.

kalshi.placeOrder(...) / polymarket.submit(...)

Claude Code — minimal agent

A Claude Code session that owns one WebSocket and reacts to featured-rank updates. Drop into ~/.claude/skills/sf-agent/or run inline.

agent.ts — TypeScript / Nodesubscribe + react
import { WebSocket } from 'ws'

const ws = new WebSocket('wss://data.simplefunctions.dev/v1/ws')

ws.on('open', () => {
  ws.send(JSON.stringify({
    action: 'subscribe',
    topics: ['featured', 'ticker:KXFEDDECISION-26DEC-CUT100'],
  }))
})

ws.on('message', (raw) => {
  const frame = JSON.parse(raw.toString())
  if (frame.type === 'featured') {
    // Top-N rank update — drop into LLM context
    console.log(frame.markets.slice(0, 5).map(m => m.ticker))
  }
  if (frame.type === 'ticker') {
    // Position-level: route to your policy
    decide(frame)
  }
})

function decide(f: { ticker: string; last: number; bid: number; ask: number }) {
  if (f.ask < 0.30 && f.bid > 0.20) {
    // Liquid + contested — call agent.placeOrder via your venue connection
  }
}

OpenAI tool-use — agent function-calling

Wrap the data API as tools an LLM can call. The LLM stays language-only; a thin service owns the live socket and exposes synchronous tool surfaces.

tools.json — function schematool definitions
{
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "list_featured",
        "description": "Top-N hottest prediction markets right now, by heat score.",
        "parameters": { "type": "object", "properties": { "n": { "type": "integer" } } }
      }
    },
    {
      "type": "function",
      "function": {
        "name": "inspect_market",
        "description": "Full snapshot of a single market by ticker.",
        "parameters": { "type": "object", "properties": { "ticker": { "type": "string" } }, "required": ["ticker"] }
      }
    },
    {
      "type": "function",
      "function": {
        "name": "subscribe_ticker",
        "description": "Open a live WebSocket subscription for a ticker; subsequent calls return latest frames.",
        "parameters": { "type": "object", "properties": { "ticker": { "type": "string" } }, "required": ["ticker"] }
      }
    }
  ]
}

REST vs WebSocket for agents

Use REST for snapshots, replay, and discovery. Use WebSocket for reactive policies and live monitoring. Most agents use both.

REST
WebSocket (preferred for agents)
Freshness
Bounded by max-age cache (1–15 s)
Pushed at venue tick rate (sub-second)
Connection cost
Per-request, per-tick
One persistent connection per agent
Best for
Single shots, snapshots, replay
Reactive logic, monitoring, signal loops
Failure mode
Stale cache on origin lag
Reconnect + replay on disconnect
Throughput per agent
Bound by rate limit
Dozens of topics in one socket

FAQ

What is agentic usage of the data API?

Agentic usage means an AI agent — Claude Code, an OpenAI tool-use loop, a custom WebSocket bot, or any autonomous program — connects to the real-time prediction market data API and reacts to live frames as they arrive, rather than polling REST endpoints on a schedule.

Why does agentic usage favor WebSocket over REST?

Agents that react to events lose latency on every poll cycle and risk missing intermediate state. A WebSocket subscription pushes every frame at venue tick rate, so the agent observes the same state the venue does, with one persistent connection instead of dozens of polling threads.

How does Claude Code use this API?

A Claude Code agent can spawn the WebSocket via a tool-use call, subscribe to the topics relevant to the task (featured + a few tickers), and react to frames in its event loop. Reading frame.type and dispatching to per-topic handlers is the standard pattern.

Can OpenAI function-calling agents subscribe to the WebSocket?

Yes — wrap a small Python or Node service that owns the WebSocket and exposes function-call surface (subscribe_topic, get_latest_frame, query_candles). The LLM calls those functions; the service maintains the live socket.

What is a typical agent reaction loop?

Subscribe → on every frame, run a small policy that decides whether to act → if act, call out to the venue (or queue an operator review). The loop is simple; the value is in the policy and the freshness of the input frame.

How do agents handle disconnects and replay?

On disconnect, reconnect and resubscribe. For state continuity, fetch a fresh snapshot via GET /v1/markets/{ticker} or GET /v1/orderbook/{ticker} immediately after reconnect, then merge with incoming frames. The featured topic also force-broadcasts on registry reload.

Can multiple agents share one WebSocket connection?

They can, but typically each agent maintains its own connection — connections are cheap and isolating failure domains is cleaner. The free-tier per-IP cap is currently 5 anonymous connections; authed tiers raise the cap.

What about authentication for higher-tier agents?

Production agents pass an X-SF-API-Key header on REST and a ?key= URL parameter on WebSocket upgrade. Per-key rate limits and connection caps are enforced at the Vercel edge before the request reaches the origin.

How do I add the data API to a new agent in 30 seconds?

Open one WebSocket to wss://data.simplefunctions.dev/v1/ws, send a JSON envelope { action: "subscribe", topics: ["featured"] }, and you have a live feed of the top-N hottest markets. Add ticker and orderbook topics as the agent picks positions to track.

Does this replace the prediction market API for agents?

They serve different layers. /prediction-market-api is for queryable, normalized snapshots and metadata. /realtime-data-api is the live tick layer. Agents typically use both — query for discovery and metadata, subscribe for live state.

How do agents use heat scoring?

Heat (0–100 per market) is a single-number ranking that combines liquidity, contestation, and recent volatility. Agents use it to filter the long tail — only subscribe to markets above a heat threshold, only show the top-N to an LLM, only run signals on contested liquid contracts.

Can I run an agentic risk gate over the data API?

Yes. Poll /v1/heartbeat every 10 seconds and /v1/markets/featured every minute. If heartbeat reports degraded or featured rank distribution shifts beyond a threshold, the gate raises an alert and pauses sibling trading agents through your orchestrator.

Related surfaces