> ## 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.

# Bitquery to Codex

> Move your Bitquery integration to Codex for curated DEX data, first-class safety and PnL signals, and simpler queries

Bitquery and Codex are both GraphQL APIs over onchain data, so this is one of the smoother migrations in this section: you already think in queries, selections, and variables. The shift is in altitude. Bitquery exposes a low-level "cube" of raw datasets (trades, transfers, balance updates, instructions) that you aggregate yourself. Codex exposes curated, ready-made answers: a token's price, its safety signals, its holders, a wallet's PnL, a launchpad's lifecycle. Most of what a Bitquery integration hand-builds from raw trades, Codex returns as a field.

<Note>
  If your product depends on Bitquery's low-level surface — mempool/pending transactions, decoded logs and instructions across arbitrary contracts, ad-hoc aggregations over any onchain event, NFT trades, or non-EVM chains like Bitcoin, Tron, or Cardano — Codex is not a drop-in replacement for those. See [Gaps](#gaps) for the specifics. If you use Bitquery for DEX trades, prices, OHLCV, token metadata, holders, balances, or wallet activity, everything you rely on has a Codex equivalent, usually a shorter one.
</Note>

## Mental model

Bitquery organizes data as a cube: you enter a chain-family block (`EVM(network: eth, dataset: combined)`, `Solana`, `Tron`), pick a dataset inside it (`DEXTrades`, `DEXTradeByTokens`, `BalanceUpdates`, `Holders`, `Transfers`), and then filter, group, and aggregate the raw rows to produce the answer you want. It's powerful and general — you can compute almost anything — but you own the aggregation logic, and every query is priced by how much data it touches.

Codex is a single Supergraph of purpose-built fields. One endpoint (`https://graph.codex.io/graphql`), one auth header, and the network is a numeric `networkId` parameter. Instead of assembling candles from a trade stream, you call [`getTokenBars`](/api-reference/queries/gettokenbars). Instead of grouping `DEXTrades` by trader to compute profit, you call [`detailedWalletStats`](/api-reference/queries/detailedwalletstats). Instead of inferring "is this a scam" from raw data, you read `isScam` off the [`token`](/api-reference/queries/token).

What that means in practice:

* **You stop hand-rolling aggregations.** OHLCV, trending, holder concentration, wallet PnL, buy/sell volume splits, and multi-timeframe stats are first-class fields, not queries you assemble and maintain.
* **The network is a parameter, not a top-level block.** You stop nesting everything under `EVM(network: ...)` / `Solana`. Pass `networkId` (or `networks: [Int!]` on `balances`) and the same query covers any of [80+ networks](/networks).
* **You pull, not compute, safety and lifecycle data.** Scam flags, mint/freeze authorities, launchpad graduation, and liquidity locks are indexed and returned directly.
* **Queries get shorter.** "Give me this token's current price" is a single `getTokenPrices` call, not a trade query you sort and read the latest price from.

If you've been writing Bitquery GraphQL, the [Learn GraphQL](/learn-graphql) primer is unnecessary — you already know the mechanics. Skim [Queries](/concepts/queries) and [Subscriptions](/concepts/subscriptions) for the Codex-specific conventions (token IDs, `networkId`, cursors).

## Authentication

Bitquery's V2 API uses OAuth2: you exchange a `client_id`/`client_secret` for a short-lived Bearer token at `oauth2.bitquery.io`, then send it as `Authorization: Bearer <token>` against `https://streaming.bitquery.io/graphql`. (The legacy V1 endpoint `graphql.bitquery.io` used an `X-API-KEY` header; if your integration still uses it, you're on the old model.) Codex uses a single long-lived `Authorization` header with an API key from the [dashboard](https://dashboard.codex.io?utm_source=codex\&utm_medium=docs\&utm_campaign=migrations-bitquery) — no token-exchange step.

<CodeGroup>
  ```bash Bitquery theme={null}
  # 1. Exchange client credentials for an access token
  curl -X POST https://oauth2.bitquery.io/oauth2/token \
    -d grant_type=client_credentials \
    -d client_id=$BITQUERY_CLIENT_ID \
    -d client_secret=$BITQUERY_CLIENT_SECRET
  # → { "access_token": "ory_at_...", ... }

  # 2. Call the API with the Bearer token
  curl -X POST https://streaming.bitquery.io/graphql \
    -H "Authorization: Bearer $BITQUERY_ACCESS_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{"query":"{ EVM { DEXTrades(limit: {count: 1}) { Block { Time } } } }"}'
  ```

  ```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: \"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2\", networkId: 1 }]) { priceUsd timestamp } }"}'
  ```
</CodeGroup>

For browser-facing apps, generate a short-lived JWT with [`createApiTokens`](/api-reference/mutations/createapitokens) and pass it as `Bearer <token>`. See [Authentication](/concepts/authentication) for the full pattern.

## Endpoint mapping

Bitquery is addressed by dataset, not by URL, so this table pairs each Bitquery dataset (and the common query pattern built on it) with the Codex field that returns the same thing directly.

### DEX trades and events

| Bitquery dataset / pattern                                | Codex equivalent                                                                                                                                     | Notes                                                                                                                                                                                                                                     |
| :-------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `EVM { DEXTrades }`, `Solana { DEXTrades }`               | [`getTokenEvents`](/api-reference/queries/gettokenevents)                                                                                            | One normalized swap event per trade. `DEXTrades` is one row per swap; Codex events carry maker, amounts, USD price, and tx hash inline.                                                                                                   |
| `EVM { DEXTradeByTokens }`, `Solana { DEXTradeByTokens }` | [`getTokenEvents`](/api-reference/queries/gettokenevents) (+ [`getDetailedTokenStats`](/api-reference/queries/getdetailedtokenstats) for aggregates) | `DEXTradeByTokens` emits two rows per trade (one per side) for easier aggregation; in Codex, buy/sell breakdowns are first-class stats (token-level buy/sell counts, pair-level buy/sell volume) rather than something you group by hand. |
| `DEXTrades` filtered by `Trade.Buy.Buyer` / trader        | [`getTokenEventsForMaker`](/api-reference/queries/gettokeneventsformaker)                                                                            | Swap events for a single wallet.                                                                                                                                                                                                          |
| `Solana { Instructions }` for a DEX program               | [`getTokenEvents`](/api-reference/queries/gettokenevents) with `eventDisplayType`                                                                    | Codex decodes swap/mint/burn events for you; raw instruction decoding is a gap (see below).                                                                                                                                               |

### Prices and OHLCV

| Bitquery dataset / pattern                                                                                                             | Codex equivalent                                                                                                   | Notes                                                                                             |
| :------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------ |
| `Trade.PriceInUSD` read off the latest `DEXTrades` row                                                                                 | [`getTokenPrices`](/api-reference/queries/gettokenprices)                                                          | Direct current price by `address:networkId`; up to 25 inputs per request. No trade query to sort. |
| Historical price via `DEXTrades` at a past block/time                                                                                  | [`getTokenPrices`](/api-reference/queries/gettokenprices) with a `timestamp` input                                 | Price at a moment, without reconstructing it from trades.                                         |
| Crypto Price API `Trade { Price { Ohlc { … } } }`, or hand-rolled OHLC from `DEXTradeByTokens` bucketed by `Block { Time(interval:) }` | [`getTokenBars`](/api-reference/queries/gettokenbars) (token) / [`getBars`](/api-reference/queries/getbars) (pair) | First-class OHLCV, resolutions `1S`–`7D`. No candle assembly.                                     |

### Token data

| Bitquery dataset / pattern                         | Codex equivalent                                                                    | Notes                                                                                                |
| :------------------------------------------------- | :---------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------- |
| `Currencies` / token fields on trades              | [`token`](/api-reference/queries/token) + [`tokens`](/api-reference/queries/tokens) | Richer metadata: social links, image URLs, description, launchpad context.                           |
| `TokenSupplyUpdates` (supply)                      | `token.info` (`circulatingSupply`, `totalSupply`)                                   | Current supply on the token object.                                                                  |
| No first-class equivalent (infer from raw data)    | Safety fields on [`token`](/api-reference/queries/token)                            | `isScam`, `mintable`, `freezable`, `creatorAddress`, `top10HoldersPercent` are indexed, not derived. |
| Aggregated `DEXTradeByTokens` for volume/txn stats | [`getDetailedTokenStats`](/api-reference/queries/getdetailedtokenstats)             | Multi-timeframe volume, transactions, buy/sell counts in one call.                                   |

### Holders and balances

| Bitquery dataset / pattern                                            | Codex equivalent                                                                                                                      | Notes                                                                                                                                  |
| :-------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------- |
| `EVM { Holders }` (formerly `TokenHolders(date:)`, removed June 2026) | [`holders`](/api-reference/queries/holders) (+ [`top10HoldersPercent`](/api-reference/queries/top10holderspercent))                   | Ranked holders with balances; concentration returned on the same response. Growth or Enterprise plan.                                  |
| `BalanceUpdates` aggregated to a wallet's current holdings            | [`balances`](/api-reference/queries/balances)                                                                                         | Portfolio with USD pricing inline (`balanceUsd`, `tokenPriceUsd`); pass `networks: [Int!]`, max 200 tokens. Growth or Enterprise plan. |
| `BalanceUpdates` reconstructed at a past date                         | Not supported                                                                                                                         | Codex returns current balances; historical point-in-time balances are a gap (see below).                                               |
| `Transfers` (arbitrary token transfers)                               | [`getTokenEvents`](/api-reference/queries/gettokenevents) / [`getTokenEventsForMaker`](/api-reference/queries/gettokeneventsformaker) | Codex indexes DEX swap and lifecycle events, not arbitrary transfers. See [Gaps](#gaps).                                               |

### Wallets and traders

| Bitquery dataset / pattern                              | Codex equivalent                                                    | Notes                                                                     |
| :------------------------------------------------------ | :------------------------------------------------------------------ | :------------------------------------------------------------------------ |
| `DEXTrades` grouped by trader, PnL computed yourself    | [`detailedWalletStats`](/api-reference/queries/detailedwalletstats) | Realized PnL, volume, swap counts as first-class fields.                  |
| Wallet performance over time (hand-rolled)              | [`walletChart`](/api-reference/queries/walletchart)                 | PnL and volume time-series; resolutions `60`, `240`, `1D`, `7D`.          |
| Top traders for a token (aggregated `DEXTradeByTokens`) | [`tokenTopTraders`](/api-reference/queries/tokentoptraders)         | Top buyers/sellers/PnL, `tradingPeriod` = `DAY \| WEEK \| MONTH \| YEAR`. |
| "Find profitable wallets" (custom aggregation)          | [`filterWallets`](/api-reference/queries/filterwallets)             | Query wallets by PnL, win-rate, or volume across all networks.            |

### Discovery, pairs, and markets

| Bitquery dataset / pattern                                    | Codex equivalent                                                                                                                                                                              | Notes                                                                                                   |
| :------------------------------------------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------ |
| Aggregated `DEXTradeByTokens` ("GMGN-style" trending queries) | [`filterTokens`](/api-reference/queries/filtertokens) ranked by `trendingScore24`                                                                                                             | First-class ranked discovery; no aggregation to write. See [Discover Tokens](/recipes/discover-tokens). |
| Custom token search via `Currencies` filters                  | [`filterTokens(phrase: ...)`](/api-reference/queries/filtertokens)                                                                                                                            | Use `$SYMBOL` for exact symbol matches.                                                                 |
| DEX pool / market fields on trades                            | [`pairMetadata`](/api-reference/queries/pairmetadata), [`getDetailedPairStats`](/api-reference/queries/getdetailedpairstats), [`listPairsForToken`](/api-reference/queries/listpairsfortoken) | First-class pair concept with stats over multiple timeframes.                                           |
| Ranked pool discovery (aggregated)                            | [`filterPairs`](/api-reference/queries/filterpairs)                                                                                                                                           | Rich filter clauses across all networks.                                                                |
| DEX/protocol list (from `Trade.Dex`)                          | [`filterExchanges`](/api-reference/queries/filterexchanges)                                                                                                                                   |                                                                                                         |
| Chain list                                                    | [`getNetworks`](/api-reference/queries/getnetworks)                                                                                                                                           | Returns the `networkId`s you'll use everywhere else.                                                    |
| Block lookups (`Block` fields)                                | [`blocks`](/api-reference/queries/blocks)                                                                                                                                                     | Look up blocks by number or timestamp.                                                                  |

### Launchpads and prediction markets

| Bitquery dataset / pattern                                                         | Codex equivalent                                                                                                                              | Notes                                                                                                                                                    |
| :--------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------- |
| pump.fun via `Solana { Instructions }` (program `pump`) + `TokenSupplyUpdates`     | [`onLaunchpadTokenEvent`](/api-reference/subscriptions/onlaunchpadtokenevent) + `launchpad` fields on [`token`](/api-reference/queries/token) | Codex abstracts the full launchpad lifecycle (bonding curve, graduation, migration) instead of raw instructions. See [Launchpads](/launchpads).          |
| Polymarket via `EVM(network: matic)` events (`OrderFilled`, `ConditionResolution`) | [`filterPredictionEvents`](/api-reference/queries/filterpredictionevents) family                                                              | Higher-level event/market/trader data covering **both Polymarket and Kalshi**. Growth or Enterprise plan. See [Prediction Markets](/prediction-markets). |

## Side-by-side examples

The four patterns below are the ones most Bitquery integrations start from. Codex addresses come through as `address:networkId`; Bitquery keeps the network in the top-level block.

### 1. DEX trades for a token

<CodeGroup>
  ```graphql Bitquery theme={null}
  {
    EVM(dataset: combined, network: eth) {
      DEXTrades(
        limit: { count: 25 }
        orderBy: { descending: Block_Time }
        where: {
          Trade: { Buy: { Currency: { SmartContract: { is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } } } }
        }
      ) {
        Block { Time }
        Transaction { Hash From }
        Trade {
          Buy { Amount Price Currency { Symbol } }
          Sell { Amount Currency { Symbol } }
          Dex { ProtocolName }
        }
      }
    }
  }
  ```

  ```graphql Codex GraphQL theme={null}
  query TokenTrades {
    getTokenEvents(
      query: { address: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", networkId: 1 }
      limit: 25
    ) {
      items {
        timestamp
        eventDisplayType
        maker
        transactionHash
        data {
          ... on SwapEventData {
            amountNonLiquidityToken
            priceUsd
          }
        }
      }
      cursor
    }
  }
  ```
</CodeGroup>

For a live feed instead of polling, subscribe to [`onTokenEventsCreated`](/api-reference/subscriptions/ontokeneventscreated).

### 2. OHLCV chart

Bitquery has no stored candle — you either use the Crypto Price API's pre-aggregated `Ohlc` block or bucket `DEXTradeByTokens` by a time interval and derive open/high/low/close yourself. Codex returns bars directly.

<CodeGroup>
  ```graphql Bitquery theme={null}
  {
    EVM(network: eth, dataset: combined) {
      DEXTradeByTokens(
        orderBy: { ascendingByField: "Block_Time" }
        where: { Trade: { Currency: { SmartContract: { is: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" } } } }
      ) {
        Block { Time(interval: { count: 1, in: hours }) }
        open: Trade_PriceInUSD(minimum: Block_Time)
        high: quantile(of: Trade_PriceInUSD, level: 1.0)
        low: quantile(of: Trade_PriceInUSD, level: 0.0)
        close: Trade_PriceInUSD(maximum: Block_Time)
        volume: sum(of: Trade_Side_AmountInUSD)
      }
    }
  }
  ```

  ```graphql Codex GraphQL theme={null}
  query TokenChart {
    getTokenBars(
      symbol: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2:1"
      from: 1716595200
      to: 1717200000
      resolution: "60"
    ) {
      t
      o
      h
      l
      c
      volume
    }
  }
  ```
</CodeGroup>

Codex resolutions run `1S, 5S, 15S, 30S, 1, 5, 15, 30, 60, 240, 720, 1D, 7D` (1-second up to weekly). Sub-minute bars are retained for the last 24 hours. Layer in [`onBarsUpdated`](/api-reference/subscriptions/onbarsupdated) for live updates, and see the [Charts recipe](/recipes/charts) for a full Lightweight Charts integration.

### 3. Token holders

<CodeGroup>
  ```graphql Bitquery theme={null}
  {
    EVM(network: eth, dataset: combined) {
      Holders(
        limit: { count: 10 }
        orderBy: { descending: Balance_Amount }
        where: { Currency: { SmartContract: { is: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" } } }
      ) {
        Holder { Address }
        Balance { Amount AmountInUSD }
        Currency { Symbol }
      }
    }
  }
  ```

  ```graphql Codex GraphQL theme={null}
  query TopHolders {
    holders(input: { tokenId: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48:1" }) {
      count
      top10HoldersPercent
      items {
        address
        balance
        shiftedBalance
      }
    }
  }
  ```
</CodeGroup>

Codex returns `top10HoldersPercent` on the same response, so a concentration metric doesn't need a second query. Note that Bitquery deprecated the older `TokenHolders(date:)` dataset in June 2026 in favor of the `Holders` cube shown here; the Codex query is unaffected either way.

### 4. Wallet balances

<CodeGroup>
  ```graphql Bitquery theme={null}
  {
    EVM(network: eth, dataset: combined, aggregates: yes) {
      BalanceUpdates(
        where: { BalanceUpdate: { Address: { is: "0xd8da6bf26964af9d7eed9e03e53415d37aa96045" } } }
        orderBy: { descendingByField: "balance" }
      ) {
        Currency { Name Symbol SmartContract }
        balance: sum(of: BalanceUpdate_Amount, selectWhere: { gt: "0" })
      }
    }
  }
  ```

  ```graphql Codex GraphQL theme={null}
  query WalletBalances {
    balances(
      input: {
        walletAddress: "0xd8da6bf26964af9d7eed9e03e53415d37aa96045"
        networks: [1]
        removeScams: true
      }
    ) {
      items {
        tokenId
        shiftedBalance
        balanceUsd
        tokenPriceUsd
      }
      cursor
    }
  }
  ```
</CodeGroup>

Codex returns USD pricing inline, so you don't aggregate `BalanceUpdate_Amount` or join a separate price query. For wallet-level PnL and volume, see [`detailedWalletStats`](/api-reference/queries/detailedwalletstats) and the [Wallets recipe](/recipes/wallets).

## Real-time data

Both APIs deliver real-time data over GraphQL WebSocket subscriptions, so the mechanics port cleanly — swap the `subscription { EVM { … } }` block for the matching Codex subscription. The difference is that Codex also offers [webhooks](/concepts/webhooks) (Bitquery does not), so server-side consumers don't have to hold open a socket.

| You want updates for...       | Codex subscription                                                                                                                                                           | Codex webhook                            |
| :---------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------- |
| Token prices                  | [`onPriceUpdated`](/api-reference/subscriptions/onpriceupdated), [`onPricesUpdated`](/api-reference/subscriptions/onpricesupdated)                                           | `TOKEN_PRICE_EVENT`                      |
| OHLCV bars                    | [`onBarsUpdated`](/api-reference/subscriptions/onbarsupdated), [`onTokenBarsUpdated`](/api-reference/subscriptions/ontokenbarsupdated)                                       |                                          |
| DEX trades (token / pair)     | [`onTokenEventsCreated`](/api-reference/subscriptions/ontokeneventscreated), [`onEventsCreated`](/api-reference/subscriptions/oneventscreated)                               | `TOKEN_PAIR_EVENT`                       |
| A wallet's trades             | [`onEventsCreatedByMaker`](/api-reference/subscriptions/oneventscreatedbymaker) (input field `makerAddress`)                                                                 | `TOKEN_PAIR_EVENT` with a `maker` filter |
| Balance changes               | [`onBalanceUpdated`](/api-reference/subscriptions/onbalanceupdated)                                                                                                          | `TOKEN_TRANSFER_EVENT`                   |
| Holder count changes          | [`onHoldersUpdated`](/api-reference/subscriptions/onholdersupdated)                                                                                                          |                                          |
| New tokens / launchpad events | [`onTokenLifecycleEventsCreated`](/api-reference/subscriptions/ontokenlifecycleeventscreated), [`onLaunchpadTokenEvent`](/api-reference/subscriptions/onlaunchpadtokenevent) |                                          |
| Market cap thresholds         | [`onPricesUpdated`](/api-reference/subscriptions/onpricesupdated)                                                                                                            | `MARKET_CAP_EVENT`                       |

For enterprise-scale throughput, Bitquery offers Kafka and gRPC streams; Codex's equivalent for high-volume server-side delivery is [webhooks](/concepts/webhooks) via [`createWebhooks`](/api-reference/mutations/createwebhooks).

## Gaps

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

* **Mempool / pending transactions** (`EVM(mempool: true)`). Codex indexes confirmed onchain data, not the pending pool. If you build MEV, sandwich detection, or pre-confirmation UX, keep Bitquery or an RPC/mempool provider for that surface.
* **Raw and decoded logs, calls, and instructions across arbitrary contracts** (`Events`, `Calls`, Solana `Instructions`). Codex is a curated DEX/token API, not a general log indexer. For decoding arbitrary contract activity, pair Codex with an RPC provider or a log-indexing service.
* **Ad-hoc aggregations over any onchain field.** Bitquery's cube model lets you group and aggregate almost anything. Codex exposes fixed, purpose-built aggregates (stats, PnL, holder concentration); it doesn't run arbitrary group-bys.
* **Historical point-in-time balances.** Bitquery reconstructs a wallet's balance at any past date from `BalanceUpdates`. Codex returns current balances; for historical snapshots, combine event history yourself or keep Bitquery for that query.
* **NFT trades and collection analytics.** Codex is a fungible-token API. Pair with a dedicated NFT provider (Reservoir, OpenSea, Alchemy NFT).
* **Non-EVM/UTXO chains Codex doesn't index** (Bitcoin, Litecoin, Cardano, Tron, XRP, and others). Codex covers 80+ EVM networks plus Solana, Sui, Aptos, and Tron-family where indexed — check [Networks](/networks). For chains outside that list, keep Bitquery.
* **Kafka / gRPC stream transports.** Codex delivers real-time via WebSocket subscriptions and webhooks, not Kafka topics or gRPC.

## What you pick up

Things Codex offers that Bitquery makes you build or doesn't have:

* **First-class token safety signals.** `isScam`, `mintable`, `freezable`, `creatorAddress`, and top-holder concentration are indexed on the [`token`](/api-reference/queries/token) object. In Bitquery you'd infer these from raw supply and authority data.
* **Wallet PnL and trader discovery, ready-made.** [`detailedWalletStats`](/api-reference/queries/detailedwalletstats), [`walletChart`](/api-reference/queries/walletchart), [`tokenTopTraders`](/api-reference/queries/tokentoptraders), and [`filterWallets`](/api-reference/queries/filterwallets) return realized PnL, win-rate, and volume directly — no grouping `DEXTrades` by trader and computing profit yourself.
* **Launchpad lifecycle as an abstraction.** pump.fun, LetsBonk, Believe, and other launchpads modeled as lifecycle events with bonding-curve state, graduation, and migration — instead of raw `Instructions` you decode. See [Launchpads](/launchpads).
* **Prediction markets across venues.** Both Polymarket and Kalshi via the [`filterPredictionEvents`](/api-reference/queries/filterpredictionevents) family, at the event/market/trader level, not raw Polygon logs.
* **First-class trending and discovery.** [`filterTokens`](/api-reference/queries/filtertokens) / [`filterPairs`](/api-reference/queries/filterpairs) ranked by trending score, volume, or market cap — no "GMGN-style" aggregation query to maintain.
* **OHLCV without candle assembly.** Stored bars from 1-second to weekly via [`getTokenBars`](/api-reference/queries/gettokenbars) and [`getBars`](/api-reference/queries/getbars).
* **Simpler ergonomics.** One API-key header (no OAuth token exchange), one endpoint, a one-call `getTokenPrices`, and an official TypeScript SDK ([`@codex-data/sdk`](/sdk)). Webhooks mean server consumers don't have to hold a socket open.
* **Built for AI agents.** A [docs MCP server](/agents/docs-mcp), prebuilt [Codex Skills](/agents/codex-skills) for Claude/Cursor/Codex CLI, and pay-per-query access via [MPP](/agents/mpp).

## AI migration prompt

Bitquery integrations tend to concentrate in a few files — a GraphQL client, a set of query strings, and the aggregation code that turns raw rows into prices, candles, or PnL. 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 Bitquery touchpoint, propose a plan, and execute the migration with your approval.

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

```markdown theme={null}
You are migrating this codebase from the Bitquery GraphQL API to Codex (https://docs.codex.io). Both are GraphQL APIs, so the query mechanics carry over, but the data model is different: Bitquery exposes low-level datasets (DEXTrades, BalanceUpdates, Holders, Transfers) that the codebase aggregates itself, while Codex exposes purpose-built fields (getTokenPrices, getTokenBars, holders, detailedWalletStats) that return the finished answer. Much of the aggregation code in this repo can be deleted, not ported.

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

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

- HTTP/WebSocket calls to `streaming.bitquery.io/graphql`, `streaming.bitquery.io/eap`, `graphql.bitquery.io` (legacy V1), or `oauth2.bitquery.io`.
- OAuth token-exchange logic against `oauth2.bitquery.io/oauth2/token` (client_id/client_secret → access_token).
- Header usage of `X-API-KEY` (legacy V1) or `Authorization: Bearer` against a Bitquery host.
- Environment variables and config keys named `BITQUERY_*`, `BQ_*`, `*_CLIENT_ID`/`*_CLIENT_SECRET` used for Bitquery.
- GraphQL query/subscription strings containing chain blocks (`EVM(`, `Solana`, `Tron`) or datasets (`DEXTrades`, `DEXTradeByTokens`, `BalanceUpdates`, `Holders`, `TokenHolders`, `Transfers`, `Currencies`, `Instructions`, `TokenSupplyUpdates`).
- Aggregation/derivation code that turns Bitquery rows into prices, OHLC candles, holder concentration, or wallet PnL — this is the code most likely to be replaced by a single Codex field.
- 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 Bitquery dataset.
2. The proposed Codex equivalent for each group (use the mapping below).
3. Aggregation/derivation logic that can be deleted because Codex returns the value directly (call these out explicitly).
4. Any call sites you cannot map cleanly, flagged for human review.
5. The order you intend to make changes (shared client/auth/config first, then leaf call sites, then tests).
6. 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 is a single `Authorization: <api-key>` header for long-lived keys, or `Authorization: Bearer <jwt>` for short-lived keys. There is no OAuth token-exchange step — remove the `oauth2.bitquery.io` client-credentials flow and store one API key.
2. Prefer the official TypeScript SDK (`@codex-data/sdk`) for TS/JS projects. There is no official SDK for Python or other languages: for those, call raw GraphQL against `https://graph.codex.io/graphql`.
3. Network is a numeric parameter (`networkId`), not a top-level chain block. Convert Bitquery chain blocks to Codex network IDs: `EVM(network: eth)` → 1, `Solana` → 1399811149, `EVM(network: base)` → 8453, `bsc` → 56, `matic`/`polygon` → 137, `arbitrum` → 42161, `optimism` → 10, `avalanche` → 43114. For others, call `getNetworks` once and build a lookup.
4. Token IDs in Codex are the string `"<address>:<networkId>"`. Pair IDs use the same shape. Construct them explicitly.
5. Delete aggregation you no longer need. Replace "fetch DEXTrades and read the latest PriceInUSD" with `getTokenPrices`; "bucket DEXTradeByTokens into candles" with `getTokenBars`/`getBars`; "group DEXTrades by trader to compute profit" with `detailedWalletStats`/`walletChart`/`tokenTopTraders`; "aggregate BalanceUpdates to current holdings" with `balances` (which returns `balanceUsd`/`tokenPriceUsd` inline — do not add a separate price query).
6. `getTokenPrices` is capped at 25 inputs per request; `balances` takes `networks: [Int!]` and max 200 tokens; `holders` defaults to 50 / max 200 per page. Adjust batching and pagination accordingly.
7. For real-time, port `subscription { EVM/Solana { ... } }` blocks to the matching Codex subscription (see mapping). Use webhooks (`createWebhooks`) for server-side consumers that shouldn't hold a socket open.
8. Preserve existing public function signatures, return shapes, and error semantics wherever possible. Internal helpers can be refactored freely.
9. Update tests as you change code. If a test relied on a Bitquery response fixture, replace the fixture with a Codex equivalent rather than deleting the test.
10. When you hit a gap (mempool/pending txs, decoded logs/calls/instructions across arbitrary contracts, ad-hoc aggregations, historical point-in-time balances, NFT data, non-EVM chains Codex doesn't index like Bitcoin/Cardano/XRP, Kafka/gRPC transports), 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 what provider could fill it, and list it in your final report.

## Bitquery → Codex mapping

DEX trades and events:
- `EVM { DEXTrades }` / `Solana { DEXTrades }` → `getTokenEvents(query: { address, networkId })`
- `DEXTradeByTokens` → `getTokenEvents` (per-side buy/sell volume is first-class via `getDetailedTokenStats`, not a manual group-by)
- `DEXTrades` filtered by trader → `getTokenEventsForMaker(query: { maker, networkId })`
- Solana DEX `Instructions` → `getTokenEvents` with `eventDisplayType` (raw instruction decoding is a gap)

Prices and OHLCV:
- latest `Trade.PriceInUSD` → `getTokenPrices(inputs: [{ address, networkId }])` (≤25 inputs; add `timestamp` for historical)
- Crypto Price API `Ohlc` / hand-rolled candles from `DEXTradeByTokens` → `getTokenBars` (token) or `getBars` (pair), resolutions `1S`–`7D`

Token data:
- `Currencies` / token fields → `token` + `tokens`
- `TokenSupplyUpdates` → `token.info` (`circulatingSupply`, `totalSupply`)
- inferred safety → `isScam`, `mintable`, `freezable`, `creatorAddress`, `top10HoldersPercent` on `token`
- aggregated volume/txn stats → `getDetailedTokenStats(tokenAddress, networkId, durations: [...])`

Holders and balances:
- `Holders` (formerly `TokenHolders(date:)`, removed 2026-06-15) → `holders(input: { tokenId: "address:networkId" })` (+ `top10HoldersPercent`) — Growth/Enterprise
- `BalanceUpdates` → `balances(input: { walletAddress, networks: [networkId] })` — Growth/Enterprise; USD pricing inline
- historical point-in-time `BalanceUpdates` → not supported (flag)
- `Transfers` → `getTokenEvents` / `getTokenEventsForMaker` (DEX events only; arbitrary transfers are a gap)

Wallets and traders:
- `DEXTrades` grouped by trader → `detailedWalletStats`, `walletChart` (PnL/volume time-series), `tokenTopTraders`
- "find profitable wallets" → `filterWallets(input: { rankings: [{ attribute: realizedProfitUsd1d, direction: DESC }] })`

Discovery, pairs, markets:
- aggregated "GMGN-style" trending → `filterTokens(rankings: { attribute: trendingScore24, direction: DESC })`
- token search → `filterTokens(phrase: "$SYMBOL")`
- pool/market fields → `pairMetadata`, `getDetailedPairStats`, `listPairsForToken`, `filterPairs`
- DEX list → `filterExchanges`; chain list → `getNetworks`; blocks → `blocks`

Launchpads and prediction markets:
- pump.fun `Instructions` + `TokenSupplyUpdates` → `launchpad` fields on `token` + `onLaunchpadTokenEvent`
- Polymarket via `EVM(network: matic)` events → `filterPredictionEvents` (covers Polymarket + Kalshi) — Growth/Enterprise

Real-time (subscription → Codex subscription):
- `subscription { EVM/Solana { DEXTrades } }` → `onTokenEventsCreated` / `onEventsCreated`
- wallet trades → `onEventsCreatedByMaker` (input field `makerAddress`, not `maker`)
- prices → `onPriceUpdated` / `onPricesUpdated`
- balances → `onBalanceUpdated`; holders → `onHoldersUpdated`
- new tokens / launchpads → `onTokenLifecycleEventsCreated` / `onLaunchpadTokenEvent`

Gaps (flag, do not drop):
- mempool/pending txs (`EVM(mempool: true)`): not supported
- decoded logs/calls/instructions across arbitrary contracts: not supported (curated DEX/token API)
- ad-hoc aggregations over arbitrary fields: not supported (fixed purpose-built aggregates only)
- historical point-in-time balances: not supported
- NFT trades/collections: not supported
- non-EVM chains Codex doesn't index (Bitcoin, Cardano, XRP, etc.): not supported
- Kafka/gRPC stream transports: use WebSocket subscriptions or webhooks instead

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/auth/config, call sites, tests, docs).
2. Aggregation/derivation code deleted because Codex returns the value directly.
3. Every `TODO(migration):` you added, with file path, line, and the reason.
4. New env vars and dependencies, with the line to add to `.env.example` and the package manager command to install.
5. Bitquery integrations that were removed entirely, and what replaced them.
6. A short manual-verification checklist the human should run before merging (which features to click through, which queries 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](/api-reference/introduction) for the full schema.
* Skim the [Recipes](/recipes/discover-tokens) for end-to-end examples that solve specific product problems.
* Ask in [our community](https://t.me/codex_community) if you hit a wall during migration.
