> ## Documentation Index
> Fetch the complete documentation index at: https://docs.simplefunctions.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Real-time data cookbook

> Tested patterns for using SimpleFunctions live data in agents, dashboards, replay systems, and market-making research.

Use this cookbook when you need to assemble live market data into an agent or trading workflow. The [Real-Time Data API](/reference/realtime-data) page lists endpoints. This page shows how to combine them with the CLI and agent APIs.

Last live probe: 2026-05-06 UTC, after the data API registry-hydration deploy.

## Tested observations

The live probes produced these operational facts:

| Probe                                                          | Result                                                                                                   |
| -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `sf discover --quality --json --limit 3`                       | Returned ranked opportunities from world, contagion, cross-venue, ideas, and new markets.                |
| `sf inspect KXHORMUZWEEKLY-26MAY10-T40 --json`                 | Returned price, best bid/ask, spread, volume, indicators, regime, contagion, trend, and next actions.    |
| `sf book KXHORMUZWEEKLY-26MAY10-T40 --json`                    | Returned bid/ask levels and depth.                                                                       |
| `GET /v1/search?q=fed&limit=2`                                 | Returned autocomplete-grade Polymarket results.                                                          |
| `GET /v1/search?q=KXHORMUZWEEKLY-26MAY10-T40&limit=5&strict=0` | Hydrated and returned the exact Kalshi ticker with score `1000`.                                         |
| `GET /v1/markets/KXHORMUZWEEKLY-26MAY10-T40`                   | Hydrated and returned Kalshi metadata, last price, best bid/ask, volume, close time, and heat.           |
| `GET /v1/movers?window=1h&n=3&minVol=1000`                     | Returned live movers, mostly Polymarket in this probe.                                                   |
| `GET /v1/orderbook/KXHORMUZWEEKLY-26MAY10-T40`                 | Hydrated the market and returned non-empty bids, asks, and `ts`.                                         |
| `GET /v1/candles/KXHORMUZWEEKLY-26MAY10-T40?tf=1h&limit=5`     | Returned five 1-hour OHLCV candles.                                                                      |
| `GET /v1/trades/KXHORMUZWEEKLY-26MAY10-T40?limit=5`            | Returned an empty recent-trades array, which is normal when no recent in-memory trade prints are cached. |

Interpretation: the data-domain API is the fast feed. Exact Kalshi ticker reads can hydrate markets that were not present in the warm registry. `sf inspect` and `sf book` remain the richer analytical fallback because they add regime, indicators, suggestion, and CLI-native receipts.

## Choose the right surface

| Need                      | Use first                                        | Fallback                           |
| ------------------------- | ------------------------------------------------ | ---------------------------------- |
| Cold-start candidate list | `sf discover --quality --json`                   | `GET /v1/movers`, `GET /v1/search` |
| Ticker autocomplete       | `GET /v1/search?q=...`                           | `sf query ... --json`              |
| Agent world context       | `sf world --json`                                | `GET /api/agent/world?format=json` |
| One market dossier        | `sf inspect <ticker> --json`                     | `GET /api/agent/inspect/{ticker}`  |
| Orderbook depth           | `GET /v1/orderbook/{ticker}`                     | `sf book <ticker> --json`          |
| Fast movers               | `GET /v1/movers`                                 | `sf discover --quality --json`     |
| Historical strategy check | `sf backtest <ticker> ... --json`                | stored traces / snapshots          |
| Custom market making      | `GET /v1/orderbook`, `GET /v1/trades`, WebSocket | QuoteEngine paper mode             |

## Cold-start loop

Start broad:

```bash theme={null}
sf discover --quality --json --limit 10
```

Then inspect a candidate:

```bash theme={null}
sf inspect KXHORMUZWEEKLY-26MAY10-T40 --json
```

Then pull book depth:

```bash theme={null}
sf book KXHORMUZWEEKLY-26MAY10-T40 --json
```

For a service using HTTP only:

```bash theme={null}
curl "https://simplefunctions.dev/api/agent/world?format=json"
curl "https://simplefunctions.dev/api/agent/inspect/KXHORMUZWEEKLY-26MAY10-T40?format=json"
curl "https://data.simplefunctions.dev/v1/movers?window=1h&n=20&minVol=1000&dir=both"
```

## Data API cold start

Use data API search and movers before subscribing to individual topics:

```bash theme={null}
curl "https://data.simplefunctions.dev/v1/search?q=fed&limit=10"
curl "https://data.simplefunctions.dev/v1/movers?window=1h&n=20&minVol=1000&dir=both"
curl "https://data.simplefunctions.dev/v1/snapshot"
```

Important conventions:

| Field                    | Convention                                                                                                                            |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| Data API prices          | Decimal probabilities in `[0, 1]`.                                                                                                    |
| CLI prices               | Usually cents for human/agent trade surfaces.                                                                                         |
| `generated_at`           | Unix seconds.                                                                                                                         |
| `ts`                     | Unix milliseconds.                                                                                                                    |
| Exact Kalshi ticker miss | The API attempts direct Kalshi hydration before returning not found or an empty cache.                                                |
| Empty orderbook          | Usually invalid ticker, inactive venue book, temporary venue failure, or an actually empty market. Check `/v1/markets/{ticker}` next. |
| Empty trades             | Often just no recent in-memory trade prints for that process. It is not proof that the market has never traded.                       |

## Coverage contract

The data API has two layers:

| Layer                  | What it covers                                              | How to use it                                                                                         |
| ---------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| Warm registry          | Fast browse, featured, snapshot, movers, and common search. | Use for cold start and broad discovery.                                                               |
| Exact-ticker hydration | Valid Kalshi tickers that missed the warm registry.         | Use `/v1/markets/{ticker}`, `/v1/orderbook/{ticker}`, `/v1/candles/{ticker}`, or exact ticker search. |

Hydration is intentionally exact-ticker only. Kalshi text search parameters are not reliable enough for arbitrary query fallback, and brute-force loading every active Kalshi market would pull in too much low-signal traffic. For broad discovery, use `sf discover`, `sf query`, `/v1/search`, `/v1/movers`, and `/v1/snapshot`.

## Orderbook fallback pattern

When building a market-making or alpha pipeline, use a fallback chain:

```text theme={null}
1. Try data API: GET /v1/orderbook/{ticker}
2. If bids/asks empty, call: GET /v1/markets/{ticker}
3. If the market is missing, skip the ticker or re-run discovery.
4. If the market is active but book is empty, call: sf book <ticker> --json
5. If still empty, call: sf inspect <ticker> --json
6. If inspect says market closed, stale, or low liquidity, skip quoting.
7. If inspect says active and book is present, use the API or CLI book as the current snapshot.
```

Example shell:

```bash theme={null}
BOOK="$(curl -sS "https://data.simplefunctions.dev/v1/orderbook/KXHORMUZWEEKLY-26MAY10-T40")"
echo "$BOOK"

sf book KXHORMUZWEEKLY-26MAY10-T40 --json
sf inspect KXHORMUZWEEKLY-26MAY10-T40 --json
```

Keep this distinction in dashboards: "no cached data-domain book" is not the same as "no live market book."

## WebSocket subscription

Use WebSocket when you have a known ticker set:

```js theme={null}
const ws = new WebSocket("wss://app.simplefunctions.dev/ws")

ws.addEventListener("open", () => {
  ws.send(JSON.stringify({
    action: "subscribe",
    topics: [
      "featured",
      "ticker:KXHORMUZWEEKLY-26MAY10-T40",
      "orderbook:KXHORMUZWEEKLY-26MAY10-T40",
      "trade:KXHORMUZWEEKLY-26MAY10-T40",
      "candle:KXHORMUZWEEKLY-26MAY10-T40:1m"
    ]
  }))
})

ws.addEventListener("message", (event) => {
  const frame = JSON.parse(event.data)
  console.log(frame.type, frame)
})
```

Subscribe only after you have selected markets. For discovery, use `discover`, `movers`, `search`, or `snapshot`.

## Replay record shape

For custom research, store normalized frames:

```json theme={null}
{
  "ts": 1778040615000,
  "source": "sf.book",
  "ticker": "KXHORMUZWEEKLY-26MAY10-T40",
  "venue": "kalshi",
  "bestBid": 57,
  "bestAsk": 59,
  "bidDepth": 5434,
  "askDepth": 7997,
  "levels": {
    "bids": [[57, 209], [56, 228]],
    "asks": [[59, 1], [60, 22]]
  }
}
```

Store the source because data API, CLI book, inspect, and WebSocket frames have different coverage guarantees.

## Alpha research packet

A practical read-only packet for an agent:

```bash theme={null}
sf discover --quality --json --limit 10
sf world --delta --json --since 1h
sf inspect <ticker> --json
sf book <ticker> --json
sf backtest <ticker> --entry-below 60 --stop 35 --tp 75 --quantity 5 --days 7 --json
```

The backtest command is read-only. Treat low `dataPoints` as a warning that the result is not a full evaluation.

## Market-making packet

Before creating a quote:

```bash theme={null}
sf inspect <ticker> --json
sf book <ticker> --json
sf quoteengine status --json
sf quote list --json
```

Only after approval:

```bash theme={null}
sf quote create <ticker> --paper --spread 3 --size 5 --max-exposure 20 --stop-loss 5
```

Start with [Market making](/build/market-making) for QuoteEngine operation.

## Related docs

<CardGroup cols={2}>
  <Card title="Real-Time Data API" href="/reference/realtime-data">
    Endpoint reference and WebSocket topics.
  </Card>

  <Card title="Market making" href="/build/market-making">
    QuoteEngine workflow and operational gates.
  </Card>

  <Card title="Evaluation and replay" href="/build/evaluation-replay">
    How to evaluate agents and strategies from traces and backtests.
  </Card>

  <Card title="World Model" href="/guides/world-model">
    Agent context and delta strategy.
  </Card>
</CardGroup>
