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

# Metastreams to Codex

> Move from the Metastreams API to Codex: every Metastreams endpoint and stream mapped to its Codex query, subscription, or webhook, with side-by-side examples.

Metastreams and Codex cover the same core problem: real-time token, trade, candle, holder, and wallet data for trading apps, bots, and terminals. Every Metastreams chain is also a Codex network (Solana, BNB Smart Chain, Robinhood Chain, and Elysium), so most of your integration has a direct equivalent. This guide maps every Metastreams REST endpoint and stream channel to its Codex query, subscription, or webhook, shows working side-by-side examples for the most common patterns, and ends with a copy-paste prompt you can hand to an LLM to migrate the rest of your codebase.

## Mental model

Metastreams is a REST API at `https://api.metastreams.io/v1/...` plus one WebSocket at `wss://api.metastreams.io/v1/stream`. Each REST call takes a `chains` list of lowercase slugs (`solana`, `bsc`), lists of `tokens` or `wallets`, and costs one credit per token or wallet listed. Each stream channel (`spot.trades`, `spot.candles`, `spot.tokens`, and so on) takes a filter object. Codex is a single GraphQL Supergraph: one endpoint (`https://graph.codex.io/graphql`), one auth header, one query language, and the network is a numeric `networkId` argument on each field.

What that means in practice:

* One request can carry many reads. A Metastreams token page calls `/v1/tokens`, `/v1/ohlcv`, `/v1/trades`, and `/v1/holders`. On Codex, those four reads can go in one GraphQL request, and you only get back the fields you ask for.
* Network selection lives next to the data, so the same query shape covers the four Metastreams chains plus Ethereum, Base, Arbitrum, and [80+ more networks](https://docs.codex.io/networks.md).
* Real-time data has two delivery options instead of one. Metastreams is WebSocket only; Codex gives you [WebSocket subscriptions](https://docs.codex.io/concepts/subscriptions.md) and [webhooks](https://docs.codex.io/concepts/webhooks.md), and you can mix them in the same app.
* Billing is in [compute units](https://docs.codex.io/concepts/compute-units.md). Each query, subscription message, and webhook delivery has a listed cost on [Compute Unit Costs](https://docs.codex.io/concepts/compute-unit-costs.md), and cost does not grow with the number of tokens in a list the way Metastreams credits do.

If you've never used GraphQL, [Learn GraphQL](https://docs.codex.io/learn-graphql.md) is a 10-minute primer that's enough to follow the rest of this guide.

### Conventions that change

The data is the same; the shapes differ. Keep this table next to you while migrating.

| | Metastreams | Codex |
| :- | :- | :- |
| Network | `chains=solana`, `chains=bsc` (lowercase slugs) | `networkId: 1399811149`, `networkId: 56` |
| Token identity | `tokens` + `chains` params | `"<address>:<networkId>"` string where a `tokenId` or `symbol` is expected, otherwise `{ address, networkId }` |
| Timestamps | Unix milliseconds (`createdAt`, `timestamp`, `fromAt`) | Unix seconds (`from`, `to`, `timestamp`, `createdAt`) |
| Money | `{ native, usd }` string pairs; candles are numbers | Strings on most stats fields (`priceUSD`, `volume24`), floats on `getTokenPrices.priceUsd` and candle arrays. Parse before doing math. |
| Percents | `Pct` fields are 0 to 100 (`12.5` = 12.5%); `Bps` fields are basis points | Price changes are decimals (`0.125` = 12.5%) on `change*` fields; held-percentage filters are 0 to 100; `risk.buyTax` / `risk.sellTax` are fractions |
| Response envelope | Resource JSON; errors as `{ error: { code, message, details } }` with an HTTP status | `{ data: { <query name>: ... } }`, plus `errors` on failure, usually with HTTP 200. See [Errors & Retries](https://docs.codex.io/concepts/errors.md). |
| Pagination | `cursor` + `nextCursor` / `hasMore` | `cursor` on events, wallet trades, and balances; `offset` on `filterTokens` and other filter queries |
| Batching | Up to 100 tokens on `/v1/tokens`, 10 on most other token endpoints, 100 wallets | Array inputs (`filterTokens(tokens: [...])` up to 200, `getTokenPrices` up to 25) and GraphQL aliases |
| Unknown token | Empty list | `null` or an empty `results` list |

Codex network IDs for every Metastreams chain: `solana` → 1399811149, `bsc` → 56, `robinhood` → 4663, `elysium` → 99901. For anything else, call [`getNetworks`](https://docs.codex.io/api-reference/queries/getnetworks) once and build a lookup.

## Authentication

Metastreams sends `Authorization: Bearer meta_...`. Codex uses the same `Authorization` header with your API key from the [dashboard](https://dashboard.codex.io?utm_source=codex\&utm_medium=docs\&utm_campaign=migrations-metastreams), without the `Bearer` prefix for long-lived keys. The request body becomes GraphQL. For trying queries without writing code, use the [explorer](https://docs.codex.io/explore.md) or the "Try it" panels throughout the reference.

```bash Metastreams theme={null}
curl "https://api.metastreams.io/v1/tokens?tokens=TOKEN_ADDRESS&chains=solana" \
  -H "Authorization: Bearer $METASTREAMS_API_KEY"
```

```bash Codex theme={null}
curl https://graph.codex.io/graphql \
  -H "Authorization: $CODEX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"query":"{ getTokenPrices(inputs: [{ address: \"TOKEN_ADDRESS\", networkId: 1399811149 }]) { priceUsd timestamp address } }"}'
```

Metastreams session tokens (`POST /v1/session-tokens`) map to [`createApiTokens`](https://docs.codex.io/api-reference/mutations/createapitokens): your server mints a short-lived JWT and the browser sends it as `Authorization: Bearer <token>`. See [Authentication](https://docs.codex.io/concepts/authentication.md) for the full pattern.

## Endpoint mapping

The tables cover every Metastreams REST endpoint, grouped by what they return. The deprecated per-token paths (`/v1/tokens/{chain}/{address}/...`, `/v1/wallets/balances`, `/v1/activity`) map the same way as their collection replacements.

### Tokens, prices, and search

| Metastreams | Codex equivalent | Notes |
| :- | :- | :- |
| `GET /v1/tokens` | [`filterTokens(tokens: [...])`](https://docs.codex.io/api-reference/queries/filtertokens) or [`token`](https://docs.codex.io/api-reference/queries/token) + [`getDetailedTokenStats`](https://docs.codex.io/api-reference/queries/getdetailedtokenstats) | `filterTokens` with a `tokens` list returns metadata, price, market cap, liquidity, holder count, launchpad state, distribution percentages, and windowed stats for up to 200 tokens in one call. Use `token` + `getDetailedTokenStats` for the full multi-window picture of one token. |
| `stats` windows (`5m`, `30m`, `1h`, `6h`, `24h`) | [`getDetailedTokenStats`](https://docs.codex.io/api-reference/queries/getdetailedtokenstats) | Codex windows are 5m, 1h, 4h, 12h, 24h, and weekly, each with its own change value and unique buyer and seller counts. `30m` and `6h` have no direct twin. |
| `pools[]` on a token | [`listPairsWithMetadataForToken`](https://docs.codex.io/api-reference/queries/listpairswithmetadatafortoken) | Every pool for a token with liquidity, price, and volume. |
| `GET /v1/native-prices` | [`getTokenPrices`](https://docs.codex.io/api-reference/queries/gettokenprices) | Pass each network's wrapped native token (WSOL, WBNB, WETH) as an input. |
| `GET /v1/search` (`kind=spotToken`) | [`filterTokens(phrase: ...)`](https://docs.codex.io/api-reference/queries/filtertokens) | Address or free text. Use `$SYMBOL` for exact symbol matches, and combine with rankings and filters. |
| `GET /v1/search` (`kind=spotWallet`) | Not supported | Codex has no wallet search by name. Look wallets up by address with [`detailedWalletStats`](https://docs.codex.io/api-reference/queries/detailedwalletstats). |

### Security

| Metastreams | Codex equivalent | Notes |
| :- | :- | :- |
| `security.buyTaxBps`, `sellTaxBps` | `token.risk.buyTax`, `risk.sellTax` | Measured by executing a buy and a sell against the pool. Fractions, so multiply by 10,000 for basis points. See [Token Risk](https://docs.codex.io/concepts/token-risk.md). |
| `security.mintDisabled` | `token.mintable` | Mint authority on Solana. `token.freezable` covers freeze authority. |
| `security.lpBurntPct` | [`liquidityMetadataByToken`](https://docs.codex.io/api-reference/queries/liquiditymetadatabytoken), [`liquidityLocksV2`](https://docs.codex.io/api-reference/queries/liquiditylocksv2) | Locked and burned liquidity per token and per lock. |
| `annotations`, launchpad flags | `token.risk` (`verdict`, `score`, `reasons`) | Codex returns a risk verdict with reason codes instead of a list of annotations. |
| `security.transferBlockable`, `transferFeeBps` | `token.risk.reasons` | Partial. Blocked or pausable transfers and transfer hooks show up as reason codes (`PROOF_NON_TRANSFERABLE`, `AUTH_PAUSABLE`, `AUTH_TRANSFER_HOOK`, `PROOF_TRANSFER_FEE_100`); there is no transfer-fee number. |
| `security.dividendToken` | Not supported | No dividend-token field. |

### Holders

| Metastreams | Codex equivalent | Notes |
| :- | :- | :- |
| `GET /v1/holders` | [`holders`](https://docs.codex.io/api-reference/queries/holders) + [`filterTokenWallets`](https://docs.codex.io/api-reference/queries/filtertokenwallets) | `holders` returns the ranked balance list with `count`. `filterTokenWallets` returns per-holder realized and unrealized PnL, buy and sell volume, average cost, and labels. |
| `holders.top10Pct`, `devPct`, `sniperPct`, `bundlerPct`, `insiderPct` | `filterTokens` result fields (`top10HoldersPercent`, `devHeldPercentage`, `sniperHeldPercentage`, `bundlerHeldPercentage`, `insiderHeldPercentage`) | Also usable as `filterTokens` filters. |
| `flags` (`sniper`, `insider`, `bundler`, `dev`, `pro_trader`, ...) | Wallet labels on `filterTokenWallets` (`includeLabels` / `excludeLabels`) | See [`WalletLabel`](https://docs.codex.io/api-reference/enums/walletlabel) for the full list, including `SMART_TRADER` and `ELITE_TRADER`. |

### Candles

| Metastreams | Codex equivalent | Notes |
| :- | :- | :- |
| `GET /v1/ohlcv` | [`getTokenBars`](https://docs.codex.io/api-reference/queries/gettokenbars) | Token-level candles from the token's pools. `from` / `to` are unix seconds; `countback` returns the newest N bars. Batch tokens with aliases. |
| `GET /v1/ohlcv?pool=...` | [`getBars`](https://docs.codex.io/api-reference/queries/getbars) | Pool-level candles; `symbol` is `"<poolAddress>:<networkId>"`. |
| `metric=marketCap` | `getTokenBars` `totalSupply` / `circulatingSupply` arrays | Multiply each bar's price by its supply for market cap. Supply is recorded on bars from 2026-10-22 onward. |

Timeframe names change. Metastreams `1s` → Codex `1S`, `5s` → `5S`, `15s` → `15S`, `30s` → `30S`, `1m` → `1`, `5m` → `5`, `15m` → `15`, `30m` → `30`, `1h` → `60`, `4h` → `240`, `12h` → `720`, `1d` → `1D`, `7d` → `7D`. Metastreams `3m` and `6h` have no direct Codex resolution; request the next finer resolution and roll up client-side. Sub-minute resolutions cover the last 24 hours. `denomination=usd` is `currencyCode: USD` on Codex; `denomination=native` is `currencyCode: TOKEN`. Metastreams omits empty buckets; set `removeEmptyBars: true` on Codex for the same behavior.

### Trades

| Metastreams | Codex equivalent | Notes |
| :- | :- | :- |
| `GET /v1/trades?tokens=...` | [`getTokenEvents`](https://docs.codex.io/api-reference/queries/gettokenevents) | Pass the token address and Codex reads its top pool; pass a pool address for one pool. Filter by maker, direction, USD size, and time range. |
| `GET /v1/trades?wallets=...` | [`walletTrades`](https://docs.codex.io/api-reference/queries/wallettrades) or [`getTokenEventsForMaker`](https://docs.codex.io/api-reference/queries/gettokeneventsformaker) | `walletTrades` returns one row per transaction with what the wallet paid and received, across networks. Metastreams caps wallet reads at 90 days. `walletTrades` trades on each network start at the time in its `coverage` field (late October 2026); use `getTokenEventsForMaker` for older swaps. |
| `GET /v1/trades?identity=kol` | [`filterWallets`](https://docs.codex.io/api-reference/queries/filterwallets) + `walletTrades` | Pick wallets by label or performance, then read their trades. |
| `POST /v1/trades` (search and sort) | [`getTokenEvents`](https://docs.codex.io/api-reference/queries/gettokenevents) | Filter by `maker`, `priceUsdTotal`, `eventDisplayType`, and `timestamp`. Codex returns events in time order; sort by size client-side. |
| `platforms` on a trade | `tradeSource` on events, `tradeSourceIds` on wallets | Which terminal or wallet app sent the swap. |

Metastreams timestamps are milliseconds; Codex `timestamp: { from, to }` is seconds.

### Wallets

| Metastreams | Codex equivalent | Notes |
| :- | :- | :- |
| `GET /v1/balances` | [`balances`](https://docs.codex.io/api-reference/queries/balances) | Holdings with USD value. `networks` is an array, so one query covers every chain. |
| `GET /v1/positions` | [`filterTokenWallets(wallets: [...])`](https://docs.codex.io/api-reference/queries/filtertokenwallets) | Per-token realized and unrealized PnL, average cost, and amounts bought and sold. Filter to rows where `tokenBalanceLive` is zero for closed positions. See [Wallet PnL](https://docs.codex.io/concepts/wallet-pnl.md) for the accounting. |
| `GET /v1/portfolio` | [`balances`](https://docs.codex.io/api-reference/queries/balances) + [`detailedWalletStats`](https://docs.codex.io/api-reference/queries/detailedwalletstats) + [`walletChart`](https://docs.codex.io/api-reference/queries/walletchart) | Holdings, the PnL summary across 1d / 1w / 30d / 1y, and the net-worth curve. |
| `identities` (name, handles) | `detailedWalletStats.wallet` | `displayName`, `avatarUrl`, `identityLabels`, and `twitterUsername` / `telegramUsername` / `farcasterUsername`. |
| `funding`, `devFunding` | `detailedWalletStats.wallet.firstFunding` | The first inbound transfer that funded the wallet. |

### Discovery and trending

Metastreams' discovery boards (`newPairs`, `graduating`, `graduated`), trending boards, and token search all collapse into one Codex query: [`filterTokens`](https://docs.codex.io/api-reference/queries/filtertokens). It filters and ranks across 100+ attributes in one request, including price, market cap, liquidity, windowed volume and transaction counts, holders, age, held percentages, launchpad state, and creator.

| Metastreams | Codex equivalent | Notes |
| :- | :- | :- |
| `POST /v1/discovery` `newPairs` | `filterTokens` with `launchpadGraduationPercent: { lt: 40 }`, `launchpadCompleted: false`, ranked by `createdAt` | Metastreams defines `newPairs` as below 40% bonding curve. |
| `POST /v1/discovery` `graduating` | `filterTokens` with `launchpadGraduationPercent: { gte: 40 }`, `launchpadMigrated: false` | Add `liquidity`, `marketCap`, and `holders` filters to match Metastreams' defaults ($1,000, $5,000, and 10 holders). |
| `POST /v1/discovery` `graduated` | `filterTokens` with `launchpadMigrated: true`, ranked by `launchpadMigratedAt` | |
| `POST /v1/trending` | `filterTokens` ranked by `trendingScore` windows (`trendingScore5m`, `trendingScore1`, `trendingScore24`, ...) | Ranks tokens by a trending score per window. Codex has no 30m window. |
| Discovery filters | `filterTokens` filters | `liquidityUsd` → `liquidity`, `marketCapUsd` → `marketCap`, `holderCount` → `holders`, `ageMinutes` → `createdAt` (a unix-seconds cutoff, now minus the age), `volumeUsd` → `volume*`, `txns` → `txnCount*`, `top10HoldersPercent` → `top10HoldersPercent`, `snipersSupplyPercent` → `sniperHeldPercentage`, `bundlerSupplyPercent` → `bundlerHeldPercentage`, `insiderSupplyPercent` → `insiderHeldPercentage`, `devHoldingPercent` → `devHeldPercentage`, `protocols` → `launchpadProtocol`. |

> [!TIP]
>
> `filterTokens` has a real-time twin: [`onFilterTokensUpdated`](https://docs.codex.io/api-reference/subscriptions/onfiltertokensupdated) pushes the live, re-ranked result set for a filter as the market moves. It replaces the `spot.discovery` and `spot.trending` streams. See the [Launchpads recipe](https://docs.codex.io/recipes/launchpads.md) and [Discover Tokens recipe](https://docs.codex.io/recipes/discover-tokens.md) for worked examples.

## Side-by-side examples

The five patterns below are the ones trading apps migrate first. Replace `TOKEN_ADDRESS` and `WALLET_ADDRESS` with your own values.

### 1. Token snapshot (metadata + price + stats)

Metastreams returns this from `GET /v1/tokens`. On Codex, `filterTokens` with a `tokens` list returns the same picture for up to 200 tokens in one call.

```bash Metastreams theme={null}
curl "https://api.metastreams.io/v1/tokens?tokens=TOKEN_ADDRESS&chains=solana" \
  -H "Authorization: Bearer $METASTREAMS_API_KEY"
```

```graphql Codex GraphQL theme={null}
query TokenSnapshot {
  filterTokens(
    tokens: ["TOKEN_ADDRESS:1399811149"]
    limit: 1
  ) {
    results {
      token {
        address
        name
        symbol
        decimals
        createdAt
        creatorAddress
        info {
          totalSupply
          circulatingSupply
          imageLargeUrl
          description
        }
        socialLinks {
          twitter
          telegram
          website
        }
        launchpad {
          launchpadName
          graduationPercent
          completed
          migrated
        }
      }
      priceUSD
      marketCap
      liquidity
      holders
      top10HoldersPercent
      sniperHeldPercentage
      bundlerHeldPercentage
      devHeldPercentage
      volume24
      buyCount24
      sellCount24
      change24
    }
  }
}
```

```typescript Codex SDK theme={null}
import { Codex } from "@codex-data/sdk"

const sdk = new Codex(process.env.CODEX_API_KEY!)

const { filterTokens } = await sdk.queries.filterTokens({
  tokens: ["TOKEN_ADDRESS:1399811149"],
  limit: 1,
})

const t = filterTokens?.results?.[0]
console.log(t?.token?.symbol, t?.priceUSD, t?.marketCap, t?.change24)
```

`change24` is a decimal (`0.0375` = 3.75%), and `priceUSD`, `marketCap`, and `volume24` are strings. For safety data (Metastreams' `security` object), add `risk { verdict reasons buyTax sellTax }` to the `token` selection, or query [`token`](https://docs.codex.io/api-reference/queries/token) directly. The [Detailed Token Page recipe](https://docs.codex.io/recipes/detailed-token-page.md) shows the full pattern.

### 2. OHLCV chart

```bash Metastreams theme={null}
curl "https://api.metastreams.io/v1/ohlcv?tokens=TOKEN_ADDRESS&chains=solana&timeframe=1h&metric=price&countBack=24" \
  -H "Authorization: Bearer $METASTREAMS_API_KEY"
```

```graphql Codex GraphQL theme={null}
query TokenChart {
  getTokenBars(
    symbol: "TOKEN_ADDRESS:1399811149"
    from: 1764633600
    to: 1764720000
    resolution: "60"
    currencyCode: USD
    countback: 24
    removeEmptyBars: true
  ) {
    t
    o
    h
    l
    c
    volume
    circulatingSupply
  }
}
```

Metastreams returns one object per candle; Codex returns parallel arrays (`t[i]`, `o[i]`, `h[i]`, and so on). Metastreams charts default to `metric=marketCap`; on Codex, multiply each price by `circulatingSupply[i]` (or `totalSupply[i]` for fully diluted). For live candles, layer in [`onTokenBarsUpdated`](https://docs.codex.io/api-reference/subscriptions/ontokenbarsupdated). See the [Charts recipe](https://docs.codex.io/recipes/charts.md) for a full Lightweight Charts integration.

### 3. Trade tape, then stream it

```bash Metastreams theme={null}
curl "https://api.metastreams.io/v1/trades?tokens=TOKEN_ADDRESS&chains=solana&limit=50" \
  -H "Authorization: Bearer $METASTREAMS_API_KEY"

# Live: send over wss://api.metastreams.io/v1/stream
# { "action": "subscribe", "channel": "spot.trades",
#   "filters": { "chains": ["solana"], "tokens": ["TOKEN_ADDRESS"] } }
```

```graphql Codex GraphQL theme={null}
query TradeTape {
  getTokenEvents(
    query: {
      address: "TOKEN_ADDRESS"
      networkId: 1399811149
      eventType: Swap
    }
    limit: 50
  ) {
    items {
      timestamp
      transactionHash
      blockNumber
      logIndex
      maker
      eventDisplayType
      tradeSource {
        id
        displayName
      }
      data {
        ... on SwapEventData {
          amount0
          amount1
          priceUsd
          priceUsdTotal
        }
      }
    }
    cursor
  }
}
```

```graphql Codex subscription theme={null}
subscription LiveTape {
  onTokenEventsCreated(
    input: { tokenAddress: "TOKEN_ADDRESS", networkId: 1399811149 }
  ) {
    events {
      timestamp
      transactionHash
      maker
      eventDisplayType
      data {
        ... on SwapEventData {
          priceUsdTotal
        }
      }
    }
  }
}
```

Metastreams streams send only updates after you subscribe and do not replay missed frames, so their docs describe a subscribe, buffer, read REST, merge procedure. The same pattern works on Codex: open [`onTokenEventsCreated`](https://docs.codex.io/api-reference/subscriptions/ontokeneventscreated), then backfill with [`getTokenEvents`](https://docs.codex.io/api-reference/queries/gettokenevents) using `timestamp: { from }` set a couple of seconds before your last seen event, and dedupe on `transactionHash` + `logIndex`. See the [Events recipe](https://docs.codex.io/recipes/events.md).

### 4. Wallet trades and holdings

Metastreams splits this across `/v1/trades?wallets=`, `/v1/balances`, and `/v1/positions`. On Codex, one request returns the wallet's recent trades and its holdings.

```bash Metastreams theme={null}
curl "https://api.metastreams.io/v1/trades?wallets=WALLET_ADDRESS&chains=solana" \
  -H "Authorization: Bearer $METASTREAMS_API_KEY"

curl "https://api.metastreams.io/v1/balances?wallets=WALLET_ADDRESS&chains=solana" \
  -H "Authorization: Bearer $METASTREAMS_API_KEY"
```

```graphql Codex GraphQL theme={null}
query WalletOverview {
  walletTrades(
    input: { walletAddress: "WALLET_ADDRESS", networkIds: [1399811149] }
    limit: 50
  ) {
    items {
      timestamp
      transactionHash
      side
      tokenAddress
      tokenAmount
      valueUsd
      tokenPriceUsd
    }
    cursor
  }
  balances(
    input: {
      walletAddress: "WALLET_ADDRESS"
      networks: [1399811149]
      removeScams: true
    }
  ) {
    items {
      tokenId
      shiftedBalance
      balanceUsd
      tokenPriceUsd
    }
    cursor
  }
}
```

For per-token positions with average cost and realized and unrealized PnL (Metastreams' `/v1/positions`), use [`filterTokenWallets`](https://docs.codex.io/api-reference/queries/filtertokenwallets) with `wallets: [...]`. For the PnL summary, use [`detailedWalletStats`](https://docs.codex.io/api-reference/queries/detailedwalletstats). See the [Trader Dashboard recipe](https://docs.codex.io/recipes/wallets/trader-dashboard.md) for the full screen.

### 5. Discovery board column

Metastreams' `graduating` column with liquidity and holder filters, as one Codex query.

```bash Metastreams theme={null}
curl -X POST "https://api.metastreams.io/v1/discovery" \
  -H "Authorization: Bearer $METASTREAMS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "chains": ["solana", "bsc"],
    "graduating": {
      "sortBy": "volume24hUsd",
      "limit": 20,
      "filters": { "liquidityUsd": { "min": "20000" }, "holderCount": { "min": 500 } }
    }
  }'
```

```graphql Codex GraphQL theme={null}
query GraduatingColumn {
  filterTokens(
    filters: {
      network: [1399811149, 56]
      launchpadGraduationPercent: { gte: 40 }
      launchpadMigrated: false
      liquidity: { gte: 20000 }
      holders: { gte: 500 }
    }
    rankings: [{ attribute: volume24, direction: DESC }]
    limit: 20
  ) {
    results {
      token {
        address
        name
        symbol
        networkId
        launchpad {
          launchpadName
          graduationPercent
        }
      }
      priceUSD
      marketCap
      liquidity
      holders
      volume24
    }
  }
}
```

Swap `query` for `subscription` and `filterTokens` for [`onFilterTokensUpdated`](https://docs.codex.io/api-reference/subscriptions/onfiltertokensupdated) to keep the column live, like `spot.discovery`.

## Real-time data

Metastreams streams over one WebSocket at `wss://api.metastreams.io/v1/stream` with `subscribe` / `unsubscribe` / `ping` actions, a 30-second ping you send, and per-key limits of 20 connections, 20 subscriptions, and 2,000 addresses. Subscriptions do not survive a reconnect. Codex gives you the same data with two delivery options, and you can use both at once:

* [WebSocket subscriptions](https://docs.codex.io/concepts/subscriptions.md): persistent connection, updates pushed inline, API key in the connection init. Best for dashboards, trading UIs, and anything user-facing. Growth plans get 300 connections per key, and each connection can carry many subscriptions.
* [Webhooks](https://docs.codex.io/concepts/webhooks.md): Codex calls an HTTP endpoint you control when an event fires. Best for alerts, background jobs, and queue-driven systems. Metastreams has no equivalent.

| Metastreams channel | Codex subscription | Codex webhook |
| :- | :- | :- |
| `spot.trades` (token, pool, or launchpad filter) | [`onTokenEventsCreated`](https://docs.codex.io/api-reference/subscriptions/ontokeneventscreated), [`onLaunchpadTokenEventBatch`](https://docs.codex.io/api-reference/subscriptions/onlaunchpadtokeneventbatch) | Token swap webhook |
| `spot.trades` (wallet filter) | [`onEventsCreatedByMaker`](https://docs.codex.io/api-reference/subscriptions/oneventscreatedbymaker) | |
| `spot.candles` | [`onTokenBarsUpdated`](https://docs.codex.io/api-reference/subscriptions/ontokenbarsupdated), [`onBarsUpdated`](https://docs.codex.io/api-reference/subscriptions/onbarsupdated) | |
| `spot.tokens` | [`onPricesUpdated`](https://docs.codex.io/api-reference/subscriptions/onpricesupdated) for price, [`onDetailedTokenStatsUpdated`](https://docs.codex.io/api-reference/subscriptions/ondetailedtokenstatsupdated) for windowed stats, [`onFilterTokensUpdated`](https://docs.codex.io/api-reference/subscriptions/onfiltertokensupdated) for a filtered set | Price webhook |
| `spot.holders` | [`onHoldersUpdated`](https://docs.codex.io/api-reference/subscriptions/onholdersupdated) | |
| `wallet.balances`, `spot.positions` | [`onBalanceUpdated`](https://docs.codex.io/api-reference/subscriptions/onbalanceupdated) | |
| `spot.discovery`, `spot.trending` | [`onFilterTokensUpdated`](https://docs.codex.io/api-reference/subscriptions/onfiltertokensupdated), [`onLatestTokens`](https://docs.codex.io/api-reference/subscriptions/onlatesttokens) | Token launch webhook |
| `chain.nativePrices` | [`onPricesUpdated`](https://docs.codex.io/api-reference/subscriptions/onpricesupdated) on each wrapped native token | |
| `spot.transfers` | Not supported | |

Cadence differs. Metastreams lets you slow a channel with `throttleMs`; Codex's `onPricesUpdated` fires once per token per block that contains a trade, and `onTokenEventsCreated` fires per swap. Each delivered message costs compute units, and each open subscription costs a small amount per minute, so scope subscriptions to what you render. See [Compute Units](https://docs.codex.io/concepts/compute-units.md#subscriptions) and [Rate Limits](https://docs.codex.io/concepts/rate-limits.md) for sizing.

## Gaps

Things Metastreams does that Codex doesn't, and what to do about them:

* **Wallet transfers** (`spot.transfers`). Codex returns swaps and token lifecycle events, not plain wallet-to-wallet transfers. Pair with an RPC provider if transfer history is core to your product.
* **Wallet search by name** (`/v1/search?kind=spotWallet`). Look wallets up by address instead.
* **Market-cap candles as a direct metric** (`metric=marketCap`). Codex bars carry supply per bar, so you multiply price by supply yourself. Bars before 2026-10-22 have no supply value.
* **Per-subscription throttling** (`throttleMs`). Codex sends every update; drop or merge frames client-side if your UI renders less often.
* **30-minute and 6-hour stats windows.** Use the nearest Codex window (1h, 4h, or 12h) or roll up candles.
* **Dividend-token and fee-allocation detail** (`dividendToken`, `fees` breakdown). No Codex field.

## What you pick up

Things Codex offers that Metastreams doesn't:

* **80+ networks, not 4.** Everything Metastreams covers plus Ethereum, Base, Arbitrum, Polygon, Sui, and dozens more, all through the same `networkId` argument. See [Networks](https://docs.codex.io/networks.md).
* **One request, many reads.** GraphQL lets you combine token metadata, price, holders, recent trades, and chart data in a single request and only pull the fields you render.
* **Webhooks.** Server-side delivery for price, swap, and launch events, alongside WebSocket subscriptions.
* **One endpoint for almost any discovery need.** [`filterTokens`](https://docs.codex.io/api-reference/queries/filtertokens) replaces the discovery boards, trending, and search, and [`onFilterTokensUpdated`](https://docs.codex.io/api-reference/subscriptions/onfiltertokensupdated) streams the same re-ranked list live.
* **Token risk verdicts.** [`token.risk`](https://docs.codex.io/concepts/token-risk) returns a verdict, score, and reason codes, plus measured buy and sell tax and sell checks on Uniswap V4 hooked pools.
* **Wallet discovery by performance.** [`filterWallets`](https://docs.codex.io/api-reference/queries/filterwallets) finds wallets by PnL, win rate, or volume across networks.
* **Prediction markets.** Polymarket and Kalshi events, markets, trades, and trader analytics, live today. See [Prediction Markets](https://docs.codex.io/prediction-markets.md).
* **Launchpad lifecycle as events.** Creation, bonding, graduation, and migration as queryable and streamable events across 200+ launchpads. See [Launchpads](https://docs.codex.io/launchpads.md).
* **Liquidity locks.** [`liquidityLocksV2`](https://docs.codex.io/api-reference/queries/liquiditylocksv2) surfaces locked-LP context across major EVM chains and Solana.
* **Official TypeScript SDK.** [`@codex-data/sdk`](https://www.npmjs.com/package/@codex-data/sdk) on npm, alongside raw GraphQL from any language.
* **Built for AI agents.** A [docs MCP server](https://docs.codex.io/agents/docs-mcp.md), prebuilt [Codex Skills](https://docs.codex.io/agents/codex-skills.md) for Claude / Cursor / Codex CLI, and pay-per-query access via [MPP](https://docs.codex.io/agents/mpp.md).

## AI migration prompt

Most Metastreams integrations span many call sites: a token service, a chart loader, a discovery board, a WebSocket handler. Hand the prompt below to an IDE agent (Claude Code, Cursor, Codex CLI, or similar), run it from the repo root, and it will find every Metastreams touchpoint, propose a plan, and run the migration with your approval.

> [!TIP]
>
> Pair this prompt with our [Codex Skills](https://docs.codex.io/agents/codex-skills.md) and [docs MCP server](https://docs.codex.io/agents/docs-mcp.md) so the agent can look up Codex queries on demand instead of guessing at field names.

```markdown theme={null}
You are migrating this codebase from Metastreams (https://docs.metastreams.io) to Codex (https://docs.codex.io). Metastreams and Codex overlap heavily on token, trade, candle, holder, and wallet data, so most call sites have a direct replacement. A few do not, and those need to be surfaced rather than silently dropped.

## Phase 1: Discovery (do this first, do not edit yet)

Search the codebase for every Metastreams integration point. At minimum, look for:

- HTTP calls to `api.metastreams.io` (any path under `/v1/...`), including `/v1/tokens`, `/v1/ohlcv`, `/v1/trades`, `/v1/holders`, `/v1/search`, `/v1/discovery`, `/v1/trending`, `/v1/balances`, `/v1/positions`, `/v1/portfolio`, `/v1/native-prices`, `/v1/session-tokens`, `/v1/stream/connect`.
- WebSocket connections to `wss://api.metastreams.io/v1/stream` (or a URL returned by `/v1/stream/connect`), the `metastreams.v1` subprotocol, and messages with `action: "subscribe"` and a `channel` such as `spot.trades`, `spot.transfers`, `spot.candles`, `spot.tokens`, `spot.holders`, `spot.positions`, `wallet.balances`, `chain.nativePrices`, `spot.trending`, or `spot.discovery`.
- The Rust crates `metastreams-sdk` and `metastreams-types`, and any client generated from `https://api.metastreams.io/openapi.json`.
- Environment variables and config keys named `METASTREAMS_*`, and keys starting with `meta_`.
- Code that builds or switches on chain slugs (`solana`, `bsc`, `robinhood`, `elysium`), reads `{ native, usd }` money pairs, `Pct` / `Bps` fields, or `nextCursor` / `hasMore`.
- Code that treats timestamps as milliseconds.
- Tests, fixtures, and mocks that reference any of the above.

Produce a Migration Plan with:

1. A grouped list of every call site, organized by Metastreams endpoint or channel.
2. The proposed Codex equivalent for each group (use the mapping below).
3. Any call sites you cannot map cleanly, flagged for human review.
4. The order you intend to make changes (shared client/config first, then leaf call sites, then tests).
5. New dependencies, env vars, and config you will introduce.

Stop and surface the plan before editing any source files. Wait for confirmation.

## Phase 2: Execution (after the plan is approved)

Ground rules:

1. Codex is a GraphQL API at `https://graph.codex.io/graphql`. Auth header is `Authorization: <api-key>` for long-lived keys (no `Bearer` prefix), or `Authorization: Bearer <jwt>` for short-lived keys made with the `createApiTokens` mutation. Metastreams session tokens map to `createApiTokens`.
2. Codex ships an official SDK for TypeScript/JavaScript only (`@codex-data/sdk`). Prefer it over hand-rolled HTTP in TS/JS projects. For Rust, Python, and every other language, use raw GraphQL over HTTP and `graphql-transport-ws` for subscriptions.
3. Network is a numeric `networkId` argument, not a chain slug: `solana` → 1399811149, `bsc` → 56, `robinhood` → 4663, `elysium` → 99901. Call `getNetworks` once and build a lookup rather than hardcoding.
4. Token IDs in Codex are the string `"<address>:<networkId>"` wherever a `tokenId` or `symbol` argument is expected (`filterTokens.tokens`, `getTokenBars.symbol`, `holders.input.tokenId`). Elsewhere pass `{ address, networkId }`.
5. Timestamps: Metastreams uses unix milliseconds; Codex uses unix seconds everywhere. Divide by 1000 on the way in and multiply on the way out.
6. Numbers: Metastreams returns money as `{ native, usd }` string pairs and percents as 0-100 `Pct` strings or `Bps` integers. Codex returns most USD stats as strings (`priceUSD`, `volume24`, `marketCap`) and price changes as decimals (`0.125` = 12.5%); `risk.buyTax` / `risk.sellTax` are fractions (multiply by 10,000 for bps). Candles come back as parallel arrays (`t`, `o`, `h`, `l`, `c`), not objects.
7. Errors: Metastreams returns `{ error: { code, message } }` with an HTTP status. Codex returns `{ data, errors }`, usually with HTTP 200. Check for `errors` in the body, not just the status code. Retry only when `extensions.retryAfterSeconds` is present.
8. Pagination: Metastreams `cursor` + `nextCursor` maps to Codex `cursor` on `getTokenEvents`, `walletTrades`, `getTokenEventsForMaker`, and `balances`. `limit` / `offset` paginates `filterTokens` and `filterTokenWallets`. `hasMore` becomes "cursor is non-null" or "results shorter than limit".
9. Batch with array inputs and GraphQL aliases. `filterTokens(tokens: [...])` takes up to 200 tokens; `getTokenPrices` takes at most 25 inputs per call, so chunk larger batches.
10. For real-time data, use WebSocket subscriptions when the consumer is a long-lived client and webhooks when the consumer is a server endpoint. Codex needs no `ping` action from the client; auth travels in the connection init. Rebuild reconnect logic so subscriptions are re-sent after a reconnect, then backfill the gap with the matching query.
11. Preserve existing public function signatures, return shapes, and error semantics wherever possible. Internal helpers can be refactored freely.
12. Update tests as you change code. If a test relied on a Metastreams response fixture, replace the fixture with a Codex equivalent rather than deleting the test.
13. When you hit a gap (wallet transfers, wallet search by name, throttleMs, dividend or fee-allocation fields), do not silently drop the feature. Leave the call site intact, add a `TODO(migration):` comment with a one-line note explaining what's missing, and list it in your final report.

## Metastreams → Codex endpoint mapping

Tokens, prices, search:
- `GET /v1/tokens` → `filterTokens(tokens: ["<address>:<networkId>", ...])` for metadata, price, market cap, liquidity, holders, launchpad state, held percentages, and stats (up to 200 tokens); or `token` + `getDetailedTokenStats` for one token in depth
- `stats` windows `5m/1h/24h` → `getDetailedTokenStats` `min5/hour1/day1`; `30m` and `6h` have no twin, use the nearest window
- `pools[]` → `listPairsWithMetadataForToken`
- `GET /v1/native-prices` → `getTokenPrices` on each network's wrapped native token
- `GET /v1/search?kind=spotToken` → `filterTokens(phrase: "...")` (`$SYMBOL` for exact symbol); `kind=spotWallet` → not supported, add a `TODO(migration):`

Security:
- `security.buyTaxBps` / `sellTaxBps` → `token.risk.buyTax` / `risk.sellTax` (fractions; null when unmeasured)
- `security.mintDisabled` → `token.mintable` (inverted); freeze authority → `token.freezable`
- `security.lpBurntPct` → `liquidityMetadataByToken` / `liquidityLocksV2`
- `annotations` → `token.risk { verdict score reasons }`
- `dividendToken`, `fees` breakdown → no Codex field, add a `TODO(migration):`

Holders:
- `GET /v1/holders` → `holders(input: { tokenId })` for ranked balances and `count`; `filterTokenWallets(tokenIds: [...])` for per-holder PnL, volumes, average cost, and labels
- `holders.top10Pct/devPct/sniperPct/bundlerPct/insiderPct` → `filterTokens` result fields `top10HoldersPercent`, `devHeldPercentage`, `sniperHeldPercentage`, `bundlerHeldPercentage`, `insiderHeldPercentage`
- holder `flags` → `filterTokenWallets` `includeLabels` / `excludeLabels` (`WalletLabel` enum)

Candles:
- `GET /v1/ohlcv` → `getTokenBars(symbol: "<address>:<networkId>", from, to, resolution, currencyCode, countback, removeEmptyBars: true)`; with `pool` → `getBars(symbol: "<poolAddress>:<networkId>", ...)`
- Timeframes: `1s`→`1S`, `5s`→`5S`, `15s`→`15S`, `30s`→`30S`, `1m`→`1`, `5m`→`5`, `15m`→`15`, `30m`→`30`, `1h`→`60`, `4h`→`240`, `12h`→`720`, `1d`→`1D`, `7d`→`7D`. `3m` and `6h` have no twin: fetch the next finer resolution and roll up.
- `denomination=usd` → `currencyCode: USD`; `native` → `currencyCode: TOKEN`
- `metric=marketCap` → multiply each bar's price by `circulatingSupply[i]` (or `totalSupply[i]`); null before 2026-10-22

Trades:
- `GET /v1/trades?tokens=` → `getTokenEvents(query: { address: <token or pool>, networkId, eventType: Swap, timestamp: { from, to }, maker }, limit, cursor)`
- `GET /v1/trades?wallets=` → `walletTrades(input: { walletAddress, networkIds, tokenAddress?, side?, timestamp? }, limit, cursor)`, one wallet per call (use aliases for several)
- `GET /v1/trades?identity=kol` → choose wallets with `filterWallets`, then `walletTrades`
- `POST /v1/trades` → `getTokenEvents` with filters; sort by size client-side
- trade `platforms` → event `tradeSource`

Wallets:
- `GET /v1/balances` → `balances(input: { walletAddress, networks: [Int!], removeScams })`
- `GET /v1/positions` → `filterTokenWallets(wallets: [...])`; closed positions are rows with `tokenBalanceLive` of zero
- `GET /v1/portfolio` → `balances` + `detailedWalletStats` + `walletChart`
- `identities` → `detailedWalletStats.wallet` (`displayName`, `identityLabels`, social usernames)
- `funding` / `devFunding` → `detailedWalletStats.wallet.firstFunding`

Discovery and trending (all collapse into `filterTokens`):
- `newPairs` → `filterTokens(filters: { launchpadGraduationPercent: { lt: 40 }, launchpadCompleted: false }, rankings: [{ attribute: createdAt, direction: DESC }])`
- `graduating` → `filterTokens(filters: { launchpadGraduationPercent: { gte: 40 }, launchpadMigrated: false })`
- `graduated` → `filterTokens(filters: { launchpadMigrated: true }, rankings: [{ attribute: launchpadMigratedAt, direction: DESC }])`
- `POST /v1/trending` → `filterTokens` ranked by `trendingScore24` (or `trendingScore1`, `trendingScore5m`)
- Discovery filters → `filterTokens` filters: `liquidityUsd`→`liquidity`, `marketCapUsd`→`marketCap`, `holderCount`→`holders`, `ageMinutes`→`createdAt: { gte: now - minutes * 60 }`, `volumeUsd`→`volume*`, `txns`→`txnCount*`, `snipersSupplyPercent`→`sniperHeldPercentage`, `bundlerSupplyPercent`→`bundlerHeldPercentage`, `insiderSupplyPercent`→`insiderHeldPercentage`, `devHoldingPercent`→`devHeldPercentage`, `protocols`→`launchpadProtocol`
- For any live board, use `onFilterTokensUpdated` rather than polling

Real-time (Metastreams channel → Codex subscription):
- `spot.trades` (token/pool) → `onTokenEventsCreated`; (launchpad) → `onLaunchpadTokenEventBatch`; (wallet) → `onEventsCreatedByMaker`
- `spot.candles` → `onTokenBarsUpdated` / `onBarsUpdated`
- `spot.tokens` → `onPricesUpdated`, `onDetailedTokenStatsUpdated`, or `onFilterTokensUpdated`
- `spot.holders` → `onHoldersUpdated`; `wallet.balances`, `spot.positions` → `onBalanceUpdated`
- `spot.discovery`, `spot.trending` → `onFilterTokensUpdated`, `onLatestTokens`
- `chain.nativePrices` → `onPricesUpdated` on wrapped native tokens
- `spot.transfers` → not supported, add a `TODO(migration):`
- Each delivered message and each open subscription minute costs compute units; scope subscriptions to what the UI renders

Gaps (flag, do not drop):
- `spot.transfers`, wallet search by name, `throttleMs`, `dividendToken`, `fees` breakdown, `30m` / `6h` stats windows

When you need details on any Codex field, fetch the reference page at `https://docs.codex.io/api-reference/queries/<name>` (or `subscriptions`, `mutations`) rather than guessing. Before migrating any real-time code, fetch `https://docs.codex.io/concepts/subscriptions` and `https://docs.codex.io/concepts/webhooks` so you pick the right delivery mechanism.

## Phase 3: Final report

When the migration is done, produce a single report with:

1. Files changed, grouped by area (client/config, call sites, tests, docs).
2. Every `TODO(migration):` you added, with file path, line, and the reason.
3. New env vars and dependencies, with the line to add to `.env.example` and the package manager command to install.
4. Metastreams integrations that were removed entirely, and what replaced them.
5. A short manual-verification checklist the human should run before merging (which features to click through, which endpoints to spot-check, which dashboards to load).

Run the project's linter and test suite before declaring the migration complete. If tests fail, fix the underlying integration, do not weaken the test.
```

## Getting help

* Browse the [API Reference](https://docs.codex.io/api-reference/introduction.md) for the full schema.
* Skim the [Recipes](https://docs.codex.io/recipes/discover-tokens.md) for end-to-end examples that solve specific product problems.
* Ask in [our community](https://discord.com/invite/mFpUhT3vAq) if you hit a wall during migration.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.