# Market overview

Ticker-style per-market stats with last and index prices, 24h stats, top-of-book, and optional sparklines.

`client.marketOverview` is the ticker surface: one row per spot market with last and optional index prices, 24-hour stats, top-of-book quotes, listing time, and optional sparklines. It uses the public transport, so no authentication is required.

Prices and quantities come back as decimal strings, already scaled to each pair's precision. Timestamps are epoch milliseconds.

## Methods

| Method                        | Summary                                                          |
| ----------------------------- | ---------------------------------------------------------------- |
| `list`                        | Fetch a page of market overview rows, sorted and filtered.       |
| `subscribe`                   | Stream the merged live set of market rows over a public channel. |
| `getSpotVolumeHistory`        | Read trailing-24-hour USD-volume samples.                        |
| `getCurrencyConversionConfig` | Read fiat and stablecoin display metadata.                       |
| `getCurrencyConversionRates`  | Read observed conversion rates and staleness.                    |

### `list(input?, options?)`

Returns `{ markets, nextPageToken }`. Every field is optional: with no input you get the top 500 markets by canonical 24-hour USD volume, descending.

```ts
await client.catalog.ensureReady();
const { markets } = await client.marketOverview.list({
	limit: 20,
	orderBy: "volume_24h_usd",
	sort: "desc",
	includeSparklines: true,
});

for (const m of markets) {
	const symbol = client.catalog.market.requirePairSymbolBySymbolId(m.symbolId);
	console.log(symbol, m.lastPrice, m.change24hBps);
}
```

Filter to specific pairs with `symbolIds`, and page through larger sets with the returned token:

```ts
const symbolId = client.catalog.market.requireSymbolIdByPairSymbol("BTC-USDT");
const first = await client.marketOverview.list({ symbolIds: [symbolId] });
const next = await client.marketOverview.list({ pageToken: first.nextPageToken });
```

#### `ListMarketOverviewInput`

| Field                | Type                      | Default            | Notes                                                |
| -------------------- | ------------------------- | ------------------ | ---------------------------------------------------- |
| `symbolIds`          | `number[]`                | `[]` (all)         | Stable IDs from 1 through 4,294,967,295.             |
| `limit`              | `number`                  | `500`              | Positive uint32 page size (1 through 4,294,967,295). |
| `pageToken`          | `string`                  | `""`               | Cursor from a previous `nextPageToken`.              |
| `orderBy`            | `"volume_24h_usd" \| ...` | `"volume_24h_usd"` | Sort key. Unvalued markets sort last.                |
| `sort`               | `"asc" \| "desc"`         | `"desc"`           | Sort direction.                                      |
| `includeSparklines`  | `boolean`                 | `true`             | Include the sparkline close series.                  |
| `sparklineIntervals` | `SparklineIntervalName[]` | `["24h"]`          | Which sparkline windows to return.                   |

### `subscribe(input)`

Streams the live set of market rows. It fetches an initial snapshot, buffers updates until ready, and emits the merged full set as an array on every change. On reconnect it refetches the snapshot before resuming. `symbolIds` filters the snapshot, buffered updates, and live publications, including after reconnect. Omit it or pass `[]` for all symbols. Returns an idempotent unsubscribe function.

```ts
const unsubscribe = client.marketOverview.subscribe({
	includeSparklines: true,
	sparklineIntervals: ["24h"],
	onEvent: (markets) => {
		// markets is the full merged MarketOverview[] on every update
		console.log(markets.length, "markets");
	},
	onError: (ctx) => console.error(ctx.channel, ctx.error),
});

// later
unsubscribe();
```

`onEvent` is required. `onOpen`, `onClose`, and `onError` are optional. See the [realtime client reference](https://testnet.polyester.com/docs/sdk/typescript/reference/realtime) for the handler contract.

### `getSpotVolumeHistory(input?, options?)`

Returns 97 aligned trailing-24-hour USD-volume samples at 15-minute intervals. With no `symbolIds`, it returns every configured pair; pass up to 2,000 distinct positive IDs to select specific pairs. The result is `{ bucket, startTsSec, endTsSec, points, pairs, totalVolumeUsd }`: `bucket` is currently `"15m"`, every pair's `volumeUsd` and `totalVolumeUsd` are decimal-string arrays ordered oldest-first, and each pair has its `symbolId`.

Samples overlap, so do not sum them to calculate traded volume for a period. The request rejects when a contributing trade cannot be valued in USD; it does not return partial or zero-filled valuations.

```ts
const history = await client.marketOverview.getSpotVolumeHistory({ symbolIds: [1, 2] });
console.log(history.totalVolumeUsd.at(-1)); // latest trailing-24h USD volume
```

### `getCurrencyConversionConfig(options?)`

Returns cacheable display metadata as `{ fiat, stablecoins }`, even before rates have been observed. Each entry has `code`, `defaultEnglishName`, `symbol`, and `fractionDigits`.

### `getCurrencyConversionRates(options?)`

Returns exact decimal-string conversion rates and backend staleness flags. Fiat rates are **currency units per USD**; stablecoin rates are **USD per stablecoin unit**.

```ts
const config = await client.marketOverview.getCurrencyConversionConfig();
const rates = await client.marketOverview.getCurrencyConversionRates();

for (const rate of rates.fiat?.rates ?? []) {
	console.log(rate.code, rate.unitsPerUsd, rates.fiat?.stale);
}
for (const rate of rates.stablecoins) {
	console.log(rate.code, rate.usdPerUnit, rate.sourceTsMs, rate.stale);
}
```

The result contains `snapshotTsMs`, optional `fiat`, and `stablecoins`. The fiat snapshot has `rates`, `sourceTsMs`, and `stale`; each fiat rate has `code` and `unitsPerUsd`. Each stablecoin rate has `code`, `usdPerUnit`, `sourceTsMs`, and `stale`. All timestamps are epoch milliseconds.

Unobserved rates remain absent. Before any observation exists, the rates request rejects as unavailable. Preserve absence and staleness in displays; do not substitute zero or assume a stablecoin is worth exactly one USD. Use decimal arithmetic when applying the rates.

## The `MarketOverview` shape

`list` rows and each element of the `subscribe` array share one parsed shape. Each row carries a stable numeric `symbolId`; resolve its display pair through the catalog.

```ts
import type {
	SparklineIntervalName,
	MarketOverview,
	MarketOverviewSparkline,
} from "@polyester/sdk";
```

`indexPrice` is absent when the venue has no positive index value. Treat absence as unavailable, not as zero. Sparkline `interval` is a `SparklineIntervalName` (`"1h" | "24h" | "1w" | "1m"`) plus `"unspecified"` on the parsed read model.

`volume24hBase` and `volume24hQuote` are absent when their scaled wire values overflow. The canonical `volume24hUsd` is also optional: it is absent when the 24-hour volume cannot be valued reliably. It is a decimal string in USD, based on execution prices and historical quarter-hour marks. Treat unavailable volumes separately from the known zero value `"0"`.

Rows for unknown or disabled catalog symbols are skipped rather than rejecting the full response or stream batch.

For freshly listed pairs, `change24hBps` may be `0` from the API. Use `getMarketOverview24hChangeDisplay(market)` to derive a display change from the sparkline when a market is under 24 hours old.

## Related

- [Market data guide](https://testnet.polyester.com/docs/sdk/typescript/guides/market-data) for the task-oriented walkthrough.
- [Streaming guide](https://testnet.polyester.com/docs/sdk/typescript/guides/streaming) for the subscription model.
- [Candles](https://testnet.polyester.com/docs/sdk/typescript/reference/candles) for OHLCV series.
- [Order book](https://testnet.polyester.com/docs/sdk/typescript/reference/order-book) for depth.
- [Public trades](https://testnet.polyester.com/docs/sdk/typescript/reference/public-trades) for prints.
